我只是没有运气将 url 编码表单值从 postman 发送到使用文件->新项目创建的普通 asp.net core 2.1 Web api。我没有做任何事情,但新的模型验证功能似乎仍然启动并向 postman 返回 400 Bad Request。谁能告诉我我做错了什么?
Controller 操作:
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
原始请求(如 fiddler 中所示):
POST http://localhost:60843/api/values HTTP/1.1
Content-Type: application/x-www-form-urlencoded
cache-control: no-cache
Postman-Token: a791eee7-63ff-4106-926f-2s67a8dcf37f
User-Agent: PostmanRuntime/7.3.0
Accept: */*
Host: localhost:60843
accept-encoding: gzip, deflate
content-length: 7
Connection: keep-alive
value=test
原始响应:
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
X-SourceFiles: =?UTF-8?BQzpcUmVwb3NcVGVzdGJlZFxNb2RlbEJpbmRpbmdcTW9kZWxCaW5kaW5nXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Thu, 25 Oct 2018 15:23:49 GMT
21
{"":["The input was not valid."]}
0
再次注意,这是 Visual Studio 2017 中 asp.net Web api 的默认模板。
一个有趣的事实是,如果我添加 Swashbuckle 并转到 swagger ui 端点并使用内置的“尝试一下”功能,它也会产生一个开箱即用的错误。
我已经让它可以与复杂类型和 json 主体一起工作,但我无法让简单类型工作,并且我尝试了各种不同的内容类型。
最佳答案
对于那些偶然发现这个问题的人,从版本 2.1 开始,默认情况下会应用自动模型绑定(bind),如果模型绑定(bind)失败,则会返回 400 Bad Request(较早版本的更改需要您检查 ModelState.IsValid 来查看模型是否有效)绑定(bind)成功)。
当将简单类型发布到 ASP.NET Core Controller 操作时,您现在必须指定它的来源。可以推断复杂类型,但不能推断像 int 和 string 这样的简单类型(如果它们位于消息正文中。如果它们位于查询字符串或路由(url)中,则推断它们)。我看到在正文本身传递值的两个选项是:
- 通过 URL 编码的表单值(将 [FromForm] 添加到操作中的参数中)
postman 的请求:
POST http://your-url/api/values HTTP/1.1
Content-Type: application/x-www-form-urlencoded
value=test
操作方法签名:
[HttpPost]
public void Post([FromForm]string value)
{
}
- 通过 json 正文(将 [FromBody] 添加到操作中的参数中)
postman 的请求:
POST http://your-url/api/values HTTP/1.1
Content-Type: application/json
"test"
操作方法签名:
[HttpPost]
public void Post([FromBody]string value)
{
}
关于c# - 在正文中使用 int/string (简单类型)发布到 asp.net core web api 2.1 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52993193/