Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 e.g. 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 ints and strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading