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...
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With