Web api post - 服务器端传递的字符串值为空
Web api post - passed string value is null at server side
我的项目是全新的Asp.net 2015 MVC6 beta 8 web 应用程序。
当我使用 C# 代码中的 post 类型调用 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);
我尝试了所有不同的编码和媒体组合,但没有任何改进。
它为空,因为无法将正文解析为字符串。内容类型是 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);
我的项目是全新的Asp.net 2015 MVC6 beta 8 web 应用程序。
当我使用 C# 代码中的 post 类型调用 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);
我尝试了所有不同的编码和媒体组合,但没有任何改进。
它为空,因为无法将正文解析为字符串。内容类型是 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);