Using HttpClient with ASMX in C#

若如初见. 提交于 2019-12-11 14:51:58

问题


I am playing with HttpClient'. I'm wondering if it is compatible with.asmx` web services.

Say I have a method such as this:

        var baseAddress = new Uri("Http://localhost/folder/WebServiceCommand.asmx/");          
        var config = new HttpSelfHostConfiguration(baseAddress);                      
        var server = new HttpSelfHostServer(config);

        using (var client = new HttpClient(server))
        {
            client.BaseAddress = baseAddress;

            var response = client.GetAsync("GetData").Result;

            Assert.IsTrue(
                        response.IsSuccessStatusCode, 
                        "Actual status code: " + response.StatusCode);
        }

Firstly, is what I'm trying to do possible or should I use the older HttpWebRequest class?

If it is possible, why is it returning a 404 - NOT FOUND? If I paste the address into a browser, it is found OK.

Thanks


回答1:


You can use the HttpClient with a Web Service ASMX endpoint

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
        httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://foo.com/GetVersion");

        var soapXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetVersion xmlns=\"http://foo.com/\" /></soap:Body></soap:Envelope>";

        var response = httpClient.PostAsync("http://foo.com/bar.asmx", new StringContent(soapXml, Encoding.UTF8, "text/xml")).Result;

        var content = response.Content.ReadAsStringAsync().Result;


来源:https://stackoverflow.com/questions/16584262/using-httpclient-with-asmx-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!