【问题标题】:post request odata with cors使用 cors 发布请求 odata
【发布时间】:2018-08-07 14:25:24
【问题描述】:

我正在使用 c#(.net framework) 和 odata V4 编写一个小服务。我的客户端是 AngularJs。 在我的本地主机上,everythink 工作正常,但是当我将代码发布到服务器(widows server 2012 R2)时,我遇到了 cors 问题。 我尝试了不同的解决方案:

  1. 尝试将Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Credentials 放入web.config,得到401500 响应预检。

  2. 添加 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


【解决方案1】:

再次检查戴安娜的链接后,我成功了。但我做出了改变。我为每个请求返回Access-Control-Allow-OriginAccess-Control-Allow-Credentials,如果它的OPTIONS 请求,我返回其余的标头:

 protected void Application_BeginRequest()
            {
                Context.Response.AddHeader("Access-Control-Allow-Origin", ORIGINS);
                Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                if (Context.Request.HttpMethod == "OPTIONS")
                {                    
                    Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST PUT, DELETE, OPTIONS");                    
                    Context.Response.End();
                }
            }

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2018-07-18
    • 2019-10-03
    • 2016-10-18
    • 2017-08-20
    • 2013-02-02
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多