Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get .NET MVC to bind POST parameters when Content-Type is text/plain

I have an IE8/IE9 CORS request using XDomainRequest of type POST coming into an ASP .NET MVC 3 web application. The linked blog post indicates that:

Only text/plain is supported for the request's Content-Type header

Now, since the Content-Type is text/plain and this is outside my control, the MVC framework will not bind the POST content parameters. It only seems to bind them when the Content-Type is application/x-www-form-urlencoded.

I cannot read the parameters from the Request object either.

I need to find a way for MVC to bind these parameters. I thought about trying to modify the Content-Type of the request on Application_BeginRequest but this didn't work.

How can I get the MVC Framework to bind the POST parameters when the Content-Type is text/plain?


Update

I believe the parameters will be available through the Request.InputStream property. I'm looking for a way to generically bind these parameters using the MVC Framework default binding. I'd prefer not to have to write a model binder for every model in my project.

like image 246
Zaid Masud Avatar asked Sep 05 '25 03:09

Zaid Masud


1 Answers

Check if:

  • You really are sending a x-www-form-urlencoded. Maybe you are sending a JSON?
  • The response includes Access-Control-Allow-Origin header

I tried the following and it worked:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_BeginRequest()
    {
        if (String.IsNullOrEmpty(Context.Request.ContentType) && Context.Request.HttpMethod == "POST")
        {
            Context.Request.ContentType = "application/x-www-form-urlencoded";
        }
    }

    protected void Application_EndRequest()
    {
        Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
    }
}

Note: For better modularity, you may want to implement Application_BeginRequest as a HTTP module and CORS (the Access-Control-Allow-Origin) as an ActionFilter

like image 102
LostInComputer Avatar answered Sep 08 '25 19:09

LostInComputer