简体   繁体   English

如何使用WebClient将多个参数发送到Web API调用

[英]How to send multiple parameters to a Web API call using WebClient

I want to send via POST request two parameters to a Web API service. 我想通过POST请求将两个参数发送到Web API服务。 I am currently receiving 404 not found when I try in the following way, as from msdn : 当我以下列方式尝试时(例如来自msdn) ,我目前收到404找不到的消息:

public static void PostString (string address)
{
    string data = "param1 = 5 param2 = " + json;
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address, method, data);

    Console.WriteLine (reply);
}

where json is a json representation of an object. 其中json是对象的json表示形式。 This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned. 这并没有工作,我曾与查询参数在尝试这个帖子 ,但没有找到相同404返回。

Can somebody provide me an example of WebClient which sends two parameters to a POST request? 有人可以给我提供一个将两个参数发送到POST请求的WebClient示例吗?

Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here ) 注意:我试图避免将两个参数都包装在同一个类中,以仅发送给服务(因为我在这里找到了建议)

I would suggest sending your parameters as a NameValueCollection . 我建议将您的参数作为NameValueCollection发送。

Your code would look something like this when sending the parameters with a NameValueCollection: 发送带有NameValueCollection的参数时,您的代码将如下所示:

using(WebClient client = new WebClient())
        {
            NameValueCollection requestParameters = new NameValueCollection();
            requestParameters.Add("param1", "5");
            requestParameters.Add("param2", json);
            byte[] response = client.UploadValues("your url here", requestParameters);
            string responseBody = Encoding.UTF8.GetString(response);
        }

Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters. 使用UploadValues将使您更轻松,因为该框架将构造请求的主体,并且您不必担心串联参数或转义字符。

I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data: 我设法通过在地址链接和json中将简单参数作为正文数据发送来发送json对象和简单值参数:

public static void PostString (string address)
{
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address + param1, method, json);

    Console.WriteLine (reply);
}

Where address needs to expect the value parameter. 地址需要包含value参数的位置。

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

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