Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting text/plain as a complex object in WebAPI with CORS

So I wish to POST (or PUT) a complex object to the server from a AJAX post using CORS. Unfortunately IE8 only supports sending text/plain when using CORS and not application/json.

Is there any way to implement a handler in WebAPI to custom parse text/plain submissions.

By complex object I mean

public void POST([FromBody] MyCustomObject myResponse)
{
   return null;
}

Normally I'd post in some JSON with the headers set appropriately but due to IE8 restrictions as soon as you set the header it fails with access denied so needs to be text/plain so what I'm planning to do is send a JSON string but called text/plain (ugly I know!) but for lack of a better option...

like image 434
John Mitchell Avatar asked Mar 25 '13 17:03

John Mitchell


2 Answers

If your WebApi application really only uses JSON, you could use this solution where it always responds with JSON and ignores the request content-type:

How can I force asp.net webapi to always decode POST data as JSON

From that, I would suggest this solution:

This code needs to be added to Application_Start or WebApiConfig.Register

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
config.Formatters.Remove(config.Formatters.XmlFormatter);

It tells the json formatter to accept the plain text content-type, and removes the form and xml formatters (although removing them may not be needed)

like image 116
truemedia Avatar answered Sep 23 '22 11:09

truemedia


ugly, but you could try modifying the content-type header from text/plain to application/json in a message handler so that parameter binding happens properly with json formatter.

like image 44
Kiran Avatar answered Sep 19 '22 11:09

Kiran