[英]C# HttpPost - field is required error (field is always null) even when provided
I have asp net core app.我有 asp net core 应用程序。 My controller looks like this:我的控制器如下所示:
[HttpPost]
public string Test(int x, int y)
{
return Request.Form["x"] + " - " + Request.Form["y"] + " | " + x + " - " + y;
}
But when i try to make post request, x and y are always 0. When I change int to eg string it gives me error "field x is required, field y is required", when i try to make post.但是当我尝试进行发布请求时,x 和 y 始终为 0。当我将 int 更改为例如字符串时,当我尝试发布时,它给我错误“字段 x 是必需的,字段 y 是必需的”。 The weird thing is Request.Form[name] gives me correct values.奇怪的是 Request.Form[name] 给了我正确的值。
For example: This POST request:例如:这个 POST 请求:
POST /api/user/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
x=123&y=5
Gives me this result:给了我这个结果:
123 - 5 | 0 - 0
It is possible to use Request.Form, but it only works for int, as I said above when i change it to string it returns code 400 with message that field is required.可以使用 Request.Form,但它仅适用于 int,正如我上面所说,当我将其更改为字符串时,它返回代码 400,并带有该字段是必需的消息。 How to fix this?如何解决这个问题?
Update your signature to be like below and let the controller know where it should get those values from for binding.将您的签名更新为如下所示,并让控制器知道它应该从哪里获取这些值以进行绑定。
[HttpPost]
public string Test([FromForm] int x, [FromForm] int y)
{
return Request.Form["x"] + " - " + Request.Form["y"] + " | " + x + " - " + y;
}
I just confirmed it with int
s and strings
.我刚刚用int
和strings
确认了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.