2017-04-14 14 views
0

我需要爲我的Web API啓用CORS,並且我無法升級到Framework 4.5。 我試過下面添加到我的web.config,看看它的工作,但事實並非如此:爲Web API啓用CORS問題1,.net 4.0

<add name="Access-Control-Allow-Origin" value="*" /> 
<add name="Access-Control-Allow-Headers" value="Accept,Content-Type,X-Requested-With"/> 

我從Ajax調用訪問URL http://localhost:8484/api/values/

並獲得波紋管錯誤

XMLHttpRequest無法加載http://localhost:8484/api/values。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。因此不允許原產地'null'訪問。響應的HTTP狀態碼爲405.

+0

你得到問題(http://stackoverflow.com/questions/22495240/iis-hijacks-cors-preflight-options-request) –

回答

3

我發現查蘭芝特·辛格這種簡單的解決方案。 它很好的工作,特別是如果你是堅持與舊的Visual Studio 2010中,在.NET 4.0,當然還有網頁API 1. 的基本上這個功能添加到您的Global.asax.cs

protected void Application_BeginRequest(object sender, EventArgs e) 

{ 

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
    { 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", 
        "GET, POST, PUT, DELETE"); 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", 
        "Content-Type, Accept"); 
     HttpContext.Current.Response.End(); 
    } 
} 

參考。鏈接:請注意,您必須滾動至答案的底部註釋。 http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html

+1

它的工作對我的感謝[動詞OPTIONS的飛行前請求] :) – Shashikant

0

Web API 1.0,您需要在Global.asax.cs文件的Application_BeginRequest事件處理程序中使用以下語句來啓用CORS支持。

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin); 

對CORS的支持可以在三個級別啓用。這些措施包括以下內容:

行動水平 控制器級別 全球一級

refer link