C# HTTP post , how to post with List<XX> parameter?

孤街浪徒 提交于 2021-01-01 06:49:18

问题


using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(url, "sign=fsadfasdf&charset=utf-8");
}

Server can get value of sign and charset.

But there is a third parameter LIST, which is a list of object (this object is an entity class). How can I pass this parameter to the server?

I tried to use "sign=fsadfasdf&charset=hhh&list=" + Json(list) as postData (convert List to json string). But the server didn't get value of this list param.


回答1:


I hate to post 1 line answers with links in them but this has been solved on here before ...

POSTing JsonObject With HttpClient From Web API

HttpClient class is designed to solve exactly this problem, i believe its found in the nuget package "Microsoft.AspNet.WebApi.Client", this should add the namespace "System.Net.Http" to your project.

It's also geared at being completely async which should be nicer to your server!

EDIT: To post an array / collection you would do something like this ...

var myObject = (dynamic)new JsonObject();
myObject.List = new List<T>();
// add items to your list

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));


来源:https://stackoverflow.com/questions/28042830/c-sharp-http-post-how-to-post-with-listxx-parameter

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