從主叫方網站,我將有此代碼:如何將請求標頭傳遞給跨域的WCF服務?
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("My-Key", '12345');
},
crossDomain: true,
xhrFields: {
withCredentials: true
},
url: "http://targetsite.com/services/myservice/mymethod",
dataType: "json",
success: function (response) {
},
error: function (message) {
}
});
在目標網站服務我有以下代碼:
public override void ProcessRequest(ref RequestContext requestContext)
{
var keys = (HttpRequestMessageProperty)
requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
string apiKey = prop.Headers["My-Key"];// this is coming null always
}
我得到apiKey空。你能讓我知道我在這裏做錯了嗎?
編輯:我這個嘗試過在我的目標網站的Global.asax.cs開始請求事件,但沒有運氣:
//Enable Cross Domain WCF Configuration
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
string rqstMethod = HttpContext.Current.Request.Headers["Access-Control-Request-Method"];
if (rqstMethod == "GET" || rqstMethod == "POST" || rqstMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "My-Key,X-Requested-With, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "3628800");
HttpContext.Current.Response.AddHeader("type", "application/json; charset=utf-8");
HttpContext.Current.Response.End();
}
您是在重述您先前的問題還是您只是不耐煩? – rene 2012-07-29 20:53:56
jsonp不允許添加自定義請求標頭:http://stackoverflow.com/questions/10546822/setrequestheader-does-not-work-in-jsonp-using-jquery – premsh 2013-06-21 23:27:03