简体   繁体   English

C# HttpPost - 字段是必需的错误(字段始终为空),即使提供

[英]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 .我刚刚用intstrings确认了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:未在模型中指示时,.net c#中的字段必填 - error:Field required in .net c# when not indicated in the model C# HttpPost-Postman Json 总是 null - C# HttpPost-Postman Json always null C#:当字段不是 null 时返回 IEnumerable? - C#: Return IEnumerable when field is not null? 在C#中对日期时间字段进行序列化时,模型始终为null-Restsharp - Model is always null when date-time field is serialized in C# - Restsharp 如果C#中显示必填字段错误消息,如何使测试失败? - How to fail the test if required field error message is displayed in c#? C#错误:非静态字段需要对象引用 - C# error : An object reference is required for the non-static field C#错误:非静态字段需要对象引用 - C# error: object reference is required for the non static field 有时,必填字段验证程序在C#中失败的情况是什么? - What are the conditions when sometimes Required field validators fails in C#? 必填字段验证程序始终显示错误消息 - Required Field Validator always shows the error message 使用隐藏的字段变量时C#字段初始化错误 - C# field initializer error when using a hidden field variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM