简体   繁体   English

如何在C#中使用WebClient将参数发布到Azure服务URL

[英]How to post parameter to Azure Service URL using WebClient in C#

I have tested/googled for hours on how to POST parameter in C# to an Azure Service without getting the Error 405. 我已经测试/搜索了数小时,以了解如何在C#中将参数POST到Azure服务,而不会出现错误405。

The following code in C++ using Chilkat lib works fine 以下使用Chilkat lib的C ++代码正常工作

CkHttp http;    
CkHttpRequest req;
http.put_SessionLogFilename("c:/temp/httpLog.txt"); 
req.put_HttpVerb("POST");
req.put_Path("/api/test?value=1234");

CkHttpResponse *resp = http.SynchronousRequest("http://testservice.cloudapp.net",80,false,req);
if (resp == 0 )
    afxDump << http.lastErrorText() << "\r\n";

afxDump << resp->bodyStr() << "\r\n";
delete resp;

But if it uses this c# code i get the Error 405. 但是,如果使用此C#代码,则会收到错误405。

string uri = "http://testservice.cloudapp.net/api/test";
string parameter = "value=1234";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(uri, parameter);
}

Any hints what i do wrong? 有什么提示我做错了吗?

You'll be better off using HttpClient instead of WebClient . 使用HttpClient而不是WebClient会更好。 By looking at what the C++ code does it should be something like this in C# using HttpClient 通过查看C ++代码的作用,它应该使用HttpClient在C#中是这样的

    public void Test() {
        using (HttpClient client = new HttpClient()) {

        client.BaseAddress = new Uri("http://testservice.cloudapp.net");
        var response = client.PostAsync("api/test?value=1234", new StringContent(string.Empty)).Result;
        var statusCode = response.StatusCode;
        var errorText = response.ReasonPhrase;

        // response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success

        var responseContentAsString = response.Content.ReadAsStringAsync().Result;
        var responseContentAsBYtes = response.Content.ReadAsByteArrayAsync().Result;
    }

}

Here is the async version of the code above 这是上面代码的异步版本

public async Task TestAsync() {
        using (HttpClient client = new HttpClient()) {

            client.BaseAddress = new Uri("http://testservice.cloudapp.net");
            var response = await client.PostAsync("api/test?value=1234", new StringContent(string.Empty));
            var statusCode = response.StatusCode;
            var errorText = response.ReasonPhrase;

            // response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success

            var responseContentAsString = await response.Content.ReadAsStringAsync();
            var responseContentAsBYtes = await response.Content.ReadAsByteArrayAsync();
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM