Cors 无法在网络中工作 api 2.0

Cors not working in web api 2.0

我正在努力理解并在 Web api 项目中启用 CORS。我遇到了障碍。我从 ASP.NET MVC Web Api 2 项目开始,具有 ASP.NET 身份。我做什么好像都不行。

我删除了我的 global.asx 文件,我的启动看起来像这样:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
          HttpConfiguration configuration = new HttpConfiguration();
          // I'm not sure it this is the proper way to use webapiconfig
          WebApiConfig.Register(configuration);
          app.UseWebApi(configuration);
          app.UseCors(CorsOptions.AllowAll);
          ConfigureAuth(app);
    }
}

并且 WebApiConfig.Register 代码是:

public static void Register(HttpConfiguration config)
{
     // Web API configuration and services
     // Configure Web API to use only bearer token authentication.
     config.SuppressDefaultHostAuthentication();
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
     config.AddODataQueryFilter();

     // Web API routes
     config.MapHttpAttributeRoutes();

     config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
     );

     var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
     jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
     RegisterModels(); //Automapper here
}

我安装了 mc aspnet cors 和 microsoft owin host System web。 “[assembly: OwinStartup(typeof(MyProject.Startup))]”已经到位,在 web.config 我有:

<appSettings>
  <add key="owin:AutomaticAppStartup" value="true" />          
</appSettings>

我只调用 app.UseCors(CorsOptions.AllowAll) 来启用 CORS,没有像 config.enableCors 或其他任何其他方式,但每当我尝试获取令牌或 API,我得到错误:

Reason: CORS header ‘Access-Control-Allow-Origin’ missing.

我曾尝试在 Configuration 方法中放置一个断点,但它从未被调用过……。我正在使用 IIS Express 进行调试。

对我来说没有任何效果.. 经过多次尝试,我终于设法让一些东西起作用了。

如果你有同样的问题..

1) 从已安装的 nugget 包中删除与 cors 相关的所有内容……所有内容。

2) 从 web.config 中删除与 cors 相关的任何内容。

3) 在 Gloabal.asax

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var context = HttpContext.Current;
        var response = context.Response;

        response.AddHeader("Access-Control-Allow-Origin", "*");
        response.AddHeader("X-Frame-Options", "ALLOW-FROM *");

        if (context.Request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PATCH, PUT");
            response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            response.AddHeader("Access-Control-Max-Age", "1000000");
            response.End();
        }
    }

这适用于 /api 和 /token。 这是一个通用解决方案,在将其部署到产品之前请注意。

希望对遇到同样问题的人有所帮助。