【问题标题】:Web api post - passed string value is null at server sideWeb api post-传递的字符串值在服务器端为空
【发布时间】:2015-10-20 05:18:28
【问题描述】:

我的项目是全新的 Asp.net 2015 MVC6 beta 8 web 应用程序。

当我从 C# 代码调用具有帖子类型的 Web api 时,我得到的值为 null。

我的服务器端代码:

// POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
            if( null != value )
                do something;
        }

我的客户端是:

StringContent cstrJson = new StringContent("{ mesage: hello}"
                                            , System.Text.Encoding.Unicode, "application/x-www-form-urlencoded");

var result = await client1.PostAsync("http://localhost:68888/api/myApi/", cstrJson);

我尝试了所有不同的编码和媒体组合,但没有任何改进。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api http-post visual-studio-2015


    【解决方案1】:

    它为空,因为无法将正文解析为字符串。内容类型是 application/x-www-form-urlencoded 而不是 text/plain。

    如果您的客户端正在发送 json,您可能需要重新考虑使用字符串,您应该在服务器上接受 application/json 并让框架为您解析它。

    [HttpPost]
    public void Post(MyObject value)
    {
        var msg = value.Message;
    }
    
    public class MyObject
    {
        public string Message { get; set; }
    }
    

    客户端:

    var cstrJson = new StringContent("{'Message' : 'hello'}", System.Text.Encoding.Unicode, "application/json");
    
    var result = await client1.PostAsync("http://localhost:68888/api/myApi/", cstrJson);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多