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

Time:07-22

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:

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?

CodePudding user response:

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.

  • Related