简体   繁体   中英

C# HttpPost - field is required error (field is always null) even when provided

I have asp net core app. 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. The weird thing is Request.Form[name] gives me correct values.

For example: This POST request:

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM