栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

通过C#中的POST发送JSON并接收返回的JSON吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过C#中的POST发送JSON并接收返回的JSON吗?

我发现自己使用HttpClient库查询RESTful
API,因为代码非常简单并且完全异步。

(编辑:为了清楚起见,从问题中添加JSON)

{  "agent": {"name": "Agent Name",         "version": 1     },  "username": "Username",    "password": "User Password",  "token": "xxxxxx"}

使用两个代表您发布的JSON结构的类,看起来像这样:

public class Credentials{    [JsonProperty("agent")]    public Agent Agent { get; set; }    [JsonProperty("username")]    public string Username { get; set; }    [JsonProperty("password")]    public string Password { get; set; }    [JsonProperty("token")]    public string Token { get; set; }}public class Agent{    [JsonProperty("name")]    public string Name { get; set; }    [JsonProperty("version")]    public int Version { get; set; }}

您可能有一个像这样的方法,它将执行您的POST请求:

var payload = new Credentials {     Agent = new Agent {         Name = "Agent Name",        Version = 1     },    Username = "Username",    Password = "User Password",    Token = "xxxxx"};// Serialize our concrete class into a JSON Stringvar stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));// Wrap our JSON inside a StringContent which then can be used by the HttpClient classvar httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");using (var httpClient = new HttpClient()) {    // Do the actual request and await the response    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);    // If the response contains content we want to read it!    if (httpResponse.Content != null) {        var responseContent = await httpResponse.Content.ReadAsStringAsync();        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号