zoukankan      html  css  js  c++  java
  • WebApi传递JSON参数

    开发过程中经常进行JSON的传递,在WebApi中传递JSON字串时,会发现服务器端接收到不参数值,看下面代码

    服务端:

    public void Post([FromBody]string value)
            {
                LoggerHelper.Info("Post:{0}", value);
            }

    客户端:

    HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string url = "http://api.oa.com/api/Test/Post";
    
                var json = "{ "Name": "Test" }";
                var httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = client.PostAsJsonAsync(url, httpContent).Result;
                if (!response.IsSuccessStatusCode)
                {
                    Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
                }

    运行客户端,查看服务端的日志,结果为“Post:”,调用成功,但参数接收失败。

    查了些资料,显示WebApi不支持JSON字串做为简单参数传递,既然如此就将JSON字串做为复杂类型进行传,对代码稍做调整,服务端接收JObject参数:

    public void Post([FromBody]JObject value)
            {
                
                LoggerHelper.Info("Post:{0}", value.ToString());
            }

    客户端:

    HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string url = "http://api.oa.com/api/Test/Post";
    
                var json = "{ "Name": "Test" }";
                var jObject = JObject.Parse(json);
                var response = client.PostAsJsonAsync(url, jObject).Result;
                if (!response.IsSuccessStatusCode)
                {
                    Response.Write(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
                }

    运行客户端,再次查看服务端的日志,结果为:

    Post:{
    "Name": "Test"
    },参数传递成功

  • 相关阅读:
    向强大的SVG迈进
    手把手教你写个小程序定时器管理库
    蒲公英 · JELLY技术周刊 Vol.11 Lighthouse 测试报告生成
    ES6语法——let和const
    北京天地益星面经
    JS的数据类型你真的懂了吗
    北京MedPeer凉经
    flex布局语法+实例
    面试官问:你有多少种方式实现三栏布局?
    CSS粘性定位
  • 原文地址:https://www.cnblogs.com/FlySoul/p/4247871.html
Copyright © 2011-2022 走看看