Home > database >  Post params from client ignored in Controller's Action (always null)
Post params from client ignored in Controller's Action (always null)

Time:12-14

Having this in Index.cshtml

  <form asp-controller="Authentication" asp-action="Test" method="post">
    <input type="text" name="titi" value="titi-val" />
    <input type="text" name="toto" value="val-toto" />
    <button type="submit">Test Submit</button>
  </form>

this

enter image description here

this in the AuthenticationController.cs

[ApiExplorerSettings(IgnoreApi = true)]
[ApiController]
[Route("api/authentication")]
public class AuthenticationController : BaseApiController
{
    [HttpPost]
    public IActionResult Test(string toto, string titi) {
        logger.LogInformation($"Test '{toto}', '{titi}'");
        return Ok(toto titi);
    }

I get this:
enter image description here

The titi field is required

and

The toto field is required

{"errors":{"titi":["The titi field is required."],"toto":["The toto field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1" , "title":"One or more validation errors occurred.","status":400,"traceId":"00-5a...03-00"}

PS.

Observed that this would work as expected

<form asp-controller="Authentication"
    asp-action="Test"
    asp-route-titi="titi-val"
    asp-route-toto="val-toto"
    method="post">

enter image description here

CodePudding user response:

API controllers does not process "simple" values from form by default. From the docs:

[FromForm] is inferred for action parameters of type IFormFile and IFormFileCollection. It's not inferred for any simple or user-defined types.

You need either to post data in some other way (json body mapped to some model or via query string parameters) or add FromForm attribute:

[HttpPost]
public IActionResult Test([FromForm] string toto, [FromForm] string titi)
{
    return Ok(toto   titi);
}
  • Related