2016-10-18 34 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分鐘)。 –