skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    Turns out that the request object contains all the hidden fields in its "Form" member which is a NameValueCollection. I declared my method like this:

     // POST: /{Controller}/Webhook
     [HttpPost]
     public virtual ActionResult Webhook()
     {
        var requestFormFields = HttpContext.Request.Form;
    

    and then I can access each field in the NameValueCollection by its name:

        var hiddenFieldValue = requestFormFields["hiddenFieldName"];
    

  2. 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)
    {
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search