C# HTTP post , 如何使用 List<XX> 发布范围? [英] C# HTTP post , how to post with List&lt;XX&gt; parameter?

查看:40
本文介绍了C# HTTP post , 如何使用 List<XX> 发布范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

但是还有第三个参数LIST,它是一个对象列表(这个对象是一个实体类).如何将此参数传递给服务器?

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?

我尝试使用 "sign=fsadfasdf&charset=hhh&list=" + Json(list) 作为 postData(将 List 转换为 json 字符串).但是服务器没有得到这个列表参数的值.

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 ...

从 Web API 使用 HttpClient 发布 JsonObject

HttpClient 类旨在解决这个问题,我相信它可以在 nuget 包Microsoft.AspNet.WebApi.Client"中找到,这应该将命名空间System.Net.Http"添加到您的项目中.

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!

要发布一个数组/集合,你会做这样的事情......

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

这篇关于C# HTTP post , 如何使用 List<XX> 发布范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆