【发布时间】:2018-08-07 14:25:24
【问题描述】:
我正在使用 c#(.net framework) 和 odata V4 编写一个小服务。我的客户端是 AngularJs。 在我的本地主机上,everythink 工作正常,但是当我将代码发布到服务器(widows server 2012 R2)时,我遇到了 cors 问题。 我尝试了不同的解决方案:
尝试将
Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Credentials放入web.config,得到401和500响应预检。添加
CorsHandler类来处理预检/添加Application_BeginRequest来处理它,没有运气(返回 Access-Control-Allow-Origin 等...)。还有这里的东西: Handling CORS Preflight requests to ASP.NET MVC actions
最后像这样尝试了 Microsoft.AspNet.WebApi.Cors 包:
var cors = new EnableCorsAttribute("cool.mydomain", "*", "*");
config.EnableCors(cors);
你猜怎么着,这也没用!
当我发送POST 方法时,我必须使用Content-Type:"x-www-form-urlencoded" 发送它,因为application/json 触发预检,并且由于某种原因不支持text/plain。我有一个使用ODataActionParameters 对象的enpoint ,并且它始终为空,假设是因为 urlencoded 的内容类型。
希望有人可以帮助我,我正在敲我的头......
【问题讨论】:
-
contentType: '应用程序/json; charset=utf-8' 通常对我有用。
-
忘了说我用的是angularjs,所以$http post方法头的默认值就是那个内容类型。我更新了我的问题
-
在您的
Application_BeginRequest方法中尝试this slightly different solution。它明确地处理odata请求。另外,请检查this detailed info about CORS。
标签: c# cors odata angularjs-http