asp.netasp.net-mvc-5x-www-form-urlencoded

ASP.Net MVC Controller accepting "application/x-www-form-urlencoded" content type


I inherited an old ASP.Net MVC web application. I need to modify it and add a page that can handle an incoming HTTP POST with hidden fields sent as "application/x-www-form-urlencoded" content type. This page's URL will be provided as a webhook URL to an external system that will use it to send back the control to my application and will provide some data in the form of "application/x-www-form-urlencoded" content type.

As I mentioned, this is an old MVC 5 application and is not targeting the .NET Core framework. Therefore I cannot declare my controller's method like this:

[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public void Webhook([FromForm] Response webHookResponse)]

The "Consumes" and "FromForm" attributes are available in the "Microsoft.AspNetCore.Mvc" namespace, but I don't have access to that in my application. Is there a different way to handle this in MVC 5?

Thanks, Ed


Solution

  • You shouldn't have to do anything. The DefaultModelBinder will bind your form values to the parameter object without specifying Consumes or FromForm attributes. The same is also true for .NET Core.

    Edit - code for clarity:

    Also an important note: this (automatic form binding) will only work if you do NOT have the [ApiController] attribute tagging your controller.

    Assume you have three hidden fields coming in, one is named foo, the other is named fudge

    Either one of these will work:

    [HttpPost]
    public void Webhook(string foo, string fudge)
    {
    }
    

    or:

    public class WbResponse
    {
    public string foo {get; set;}
    public string fudge {get; set;}
    }
    
    [HttpPost]
    public void Webhook(WbResponse response)
    {
    }