在C#中使用HttpClient和ASMX

时间:2013-05-16 09:54:07

标签: c# asmx httpclient

我正在玩HttpClient'. I'm wondering if it is compatible with。asmx`网络服务。

说我有这样的方法:

        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);
        }

首先,我正在尝试做什么,还是应该使用较旧的HttpWebRequest课程?

如果有可能,为什么它会返回404 - 未找到?如果我将地址粘贴到浏览器中,则会发现没问题。

由于

1 个答案:

答案 0 :(得分:2)

您可以将HttpClient与Web Service ASMX端点一起使用

        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;