发布文本/纯如的WebAPI一个复杂的对象,CORS [英] Posting text/plain as a complex object in WebAPI with CORS

查看:153
本文介绍了发布文本/纯如的WebAPI一个复杂的对象,CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想POST(或PUT)采用CORS从AJAX后一个复杂的对象到服务器。不幸的是IE8只支持发送纯文本/使用CORS,而不是在应用程序/ JSON

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.

有什么办法来实施的WebAPI 来定制解析text / plain的意见的处理程序。

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;
}

一般情况下我在一些JSON只要你设置它失败的访问后头部与头设置正确,但由于IE8限制,剥夺所以必须是纯文本/所以我正打算做的是送JSON字符串,但所谓的文/平原(丑我知道!),但缺乏一个更好的选项...

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...

推荐答案

如果您的应用程序的WebAPI真的只使用JSON,您可以使用此解决方案,它总是以JSON响应并忽略该请求内容类型:

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:

<一个href=\"http://stackoverflow.com/questions/12385694/how-can-i-force-asp-net-webapi-to-always-de$c$c-post-data-as-json\">How我可以强制asp.net的WebAPI总是去code POST数据作为JSON

从此,我建议此解决方案:

From that, I would suggest this solution:

这code必须添加的Application_Start或WebApiConfig.Register

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);

它告诉JSON格式接受明文内容类型,并删除的形式和xml格式化器(虽然除去可能不需要它们)

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)

这篇关于发布文本/纯如的WebAPI一个复杂的对象,CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆