[英]Cannot post primitive types in asp.net core 2.0
I'm posting very simple json data to a .net Core 2.0 API. 我将非常简单的json数据发布到.net Core 2.0 API。
Why is it when I have a method like this: 为什么我有这样的方法:
public async Task<IActionResult> GetNewToken([FromBody]string id)
Then id is null, but if I encapsulate that in a model: 然后id为null,但如果我将其封装在模型中:
public class RandomViewModel
{
public string id { get; set; }
}
public async Task<IActionResult> GetNewToken([FromBody]RandomViewModel model)
Then my id is populated correctly? 然后我的id正确填充?
You can in fact post a primitive type from request body, but you should not use the key/value, for example: 实际上,您可以从请求正文中发布基本类型,但不应使用键/值,例如:
public async Task<IActionResult> LockUserByDate(Guid appUserId, [FromBody] string lockoutEnd)
Consider this action, when I test it in Postman if I use this for the body: 考虑一下这个动作,当我在Postman中测试它时,如果我将它用于身体:
{
"lockoutEnd": "2018-03-15 16:30:35.4766052"
}
Then it dosen't bind but If I use only the value in the body, model bindler bind the value: 然后它不会绑定但如果我只使用正文中的值,模型绑定器绑定值:
"2018-06-15 16:30:35.4766052"
You can not get primitive types from your body directly like ([FromBody] string id)
if your route content type is application/json
because mvc waits model to bind json body to model not primitive types. 如果您的路由内容类型是
application/json
则不能直接从您的身体获取原始类型([FromBody] string id)
,因为mvc等待模型将json主体绑定到模型而不是基本类型。
There are some options to get primitive types from request body 有一些选项可以从请求体中获取原始类型
Changing content type to plain/text. 将内容类型更改为纯文本/文本。
Using StreamReader
to get raw token string. 使用
StreamReader
获取原始令牌字符串。
Using MVC InputFormatter
使用MVC
InputFormatter
StreamReader
Example: 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
example: https://weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers InputFormatter
示例: https : //weblog.west-wind.com/posts/2017/Sep/14/Accepting-Raw-Request-Body-Content-in-ASPNET-Core-API-Controllers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.