我剛剛創建了我的第一個WCF服務,我想與其他客戶端共享。我在IIS,Web.config和Global.asax中添加了Access-Control-Allow-Origin
標頭,但遠程客戶端仍不允許訪問該服務。我已在Chrome和IE(我們的組織支持的瀏覽器)中進行了測試。我的錯誤是「對預檢請求的響應未通過訪問控制檢查:否請求的資源上存在'Access-Control-Allow-Origin'標頭。」訪問控制允許來源是在IIS中,但不工作
在web.config中:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
</customHeaders>
</httpProtocol>
在Global.asax中:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
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.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
在這裏,他們是在IIS:
這裏的JavaScript的嘗試訪問服務。它在本地工作,但不是遠程:
$.ajax({
type: "POST",
url: "http://localhost/wsSamwise/Service1.svc/GetTime",
data: '{"UserName": "' + userName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#results").html(data.GetTimeResult);
console.log(data);
}
});
所有這些想法來自各種Stackoverflow線程,但他們都沒有爲我工作。我錯過了什麼?
編輯:我剛剛在本地主機與遠程瀏覽器簽出了響應頭。我在本地主機的響應中看到Access-Control-Allow-Origin
標題,但在遠程瀏覽器的響應中看不到該標頭。這就像它沒有被髮送。
從我的本地主機的響應報頭:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:82
Content-Type:application/json; charset=utf-8
Date:Thu, 05 May 2016 16:01:28 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
從遠程瀏覽器的響應:
Allow:OPTIONS, TRACE, GET, HEAD, POST
Content-Length:0
Date:Thu, 05 May 2016 16:00:09 GMT
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET
編輯2:夥計們,也許這是一個IIS問題完全。我只是將自定義標頭添加到IIS。它顯示在本地主機瀏覽器中,但不在客戶端上。遠程瀏覽器中缺少Body-Count
標題,但我在本地瀏覽器上看到它。
具體來說,它不工作?它是否超時?提供錯誤訊息?空的迴應? – Brian
編輯爲包含錯誤。 – mrcoulson
您是否檢查了[此鏈接](http://www.productiverage.com/wcf-cors-plus-json-rest-complete-example)? –