简体   繁体   English

如何在odata中启用CORS?

[英]How to enable CORS in odata?

I follow the step below to solve CORS issue.我按照以下步骤解决 CORS 问题。

1.Install Microsoft.AspNet.WebApi.Cors with nuget. 1.安装Microsoft.AspNet.WebApi.Cors和nuget。

2.Add code below in WebApiConfig.cs 2.在WebApiConfig.cs中添加如下代码

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

Most of API will work. API 中的大部分都可以使用。 Only oData API will still have CORS issue.只有 oData API 仍然会有 CORS 问题。

How to resolve CORS problem in oData API?如何解决 oData API 中的 CORS 问题?

edit:编辑:

After input the code below in Global.asax and it works.在 Global.asax 中输入下面的代码后,它就可以工作了。

        protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Context.Request.Path.Contains("odata/") && Context.Request.HttpMethod == "OPTIONS")
        {
            Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
            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.AddHeader("Access-Control-Allow-Credentials", "true");
            Context.Response.End();
        }
    }

Check out this answer where it says that you can try to add:看看这个答案,它说你可以尝试添加:

var cors = new EnableCorsAttribute(
    "http://localhost:7122/",
    "*",
    "*",
    "DataServiceVersion, MaxDataServiceVersion"
);
config.EnableCors(cors);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM