Search code examples
c#asp.net-core-webapix-www-form-urlencoded

c# .net core web api x-www-form-urlencoded parameter is always null


I have this method that looks a bit like this:

/// <summary>
/// Updates the status to paid
/// </summary>
/// <param name="data">The data from world pay</param>
/// <returns></returns>
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Residential([FromForm] string data)
{
    if (string.IsNullOrEmpty(data)) return BadRequest("No data was present");

    var model = JsonConvert.DeserializeObject<WorldPayResponseModel>(data);

    // ----- removed from brevity ----- //

    return Ok(true);
}

When I use postman to send some data, it is always null.

enter image description here

Does anyone have any idea why this might be?


Solution

  • Create a model/DTO for the data being posted, .net core should handle the binding (Model Binding in ASP.NET Core).

    You seem to already have WorldPayResponseModel, so why not bind to that? For example:

    public class WorldPayResponseModel
    {
        public string CardType { get; set; } 
        public int CardId { get; set; } 
        // other properties
        ...
    }
    
    [HttpPost]
    [Consumes("application/x-www-form-urlencoded")]
    public IActionResult Residential([FromForm] WorldPayResponseModel model)
    {
        if (model == null || !ModelState.IsValid) return BadRequest("No data was present");    
    
        // ----- removed from brevity ----- //
    
        return Ok(true);
    }
    

    You can also add DataAnnotations to the properties, then in the controller you can use ModelState.IsValid. Model validation in ASP.NET Core is a useful resource (it targets MVC/Razor pages, but model validation still works in an API).

    You can probably safely remove [FromForm] too.