2016-10-18 33 views
2

我很努力地理解和启用一个web api项目中的CORS。我遇到了阻碍点。我已经开始使用ASP.NET身份的ASP.NET MVC Web Api 2项目。无论我做什么似乎都行不通。Cors不工作在web api 2.0

我已经删除了我的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和微软owin主机系统网站已安装。 的 “[组件: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进行调试。

回答

3

没有为我工作..经过多次尝试我终于设法得到的东西工作。

如果你有同样的问题

..

1)从安装包金块有关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和/令牌。 这是一个通用的解决方案,请在将其部署到产品之前注意。

希望能帮助任何有同样问题的人。

+0

这是唯一对我有用的解决方案。谢谢! – alvipeo

+0

非常感谢,关于生产部署应采取的任何建议? – Lobato

+0

嗨洛巴托,如果你知道你的电话来自哪里然后改变*与该网站的起源。因为*现在意味着'Anywhere'。此外,某些apis只允许来自外部的“GET”,您必须使用他们的工具进行CRUD操作。您可以忽略更改'Access-Control-Max-Age',因为它将被浏览器特定的值覆盖。 (在Chrome中为10分钟)。 –