我将非常简单的json数据发布到.net Core 2.0 API。
为什么我有这样的方法:
public async Task<IActionResult> GetNewToken([FromBody]string id)
然后id为null,但如果我将其封装在模型中:
public class RandomViewModel
{
public string id { get; set; }
}
public async Task<IActionResult> GetNewToken([FromBody]RandomViewModel model)
然后我的id正确填充?
如果您的路由内容类型是([FromBody] string id)
,则无法直接从您的身体获取原始类型,如application/json
,因为mvc等待模型将json主体绑定到模型而不是基本类型。
有一些选项可以从请求体中获取原始类型
StreamReader
获取原始令牌字符串。InputFormatter
StreamReader
示例:
[HttpPost]
public async Task<IActionResult> GetNewToken()
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
var token = await reader.ReadToEndAsync(); // returns raw data which is sent in body
}
// your code here
}
InputFormatter
例子:https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers