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"
    },参数传递成功

  • 相关阅读:
    针式PKM软件进入华军分类下载月排名前6名
    读取xml
    一个简单的记事本程序
    python输出重定向
    重看ATL布幔之下的秘密
    nginx学习(二)动态加载各模块
    ngx_queue的理解
    nginx学习(三)IOCP的使用
    nginx学习(一)内存
    使用python实现一个通用协议测试工具
  • 原文地址:https://www.cnblogs.com/FlySoul/p/4247871.html
Copyright © 2011-2022 走看看