我有一個在Azure上託管的ASP.NET Web API。我已將HTTP消息處理程序集成到該API。當我使用AJAX調用它時,消息處理程序正在被擊中。我也在我的AJAX調用中發送一些請求頭。問題是我沒有收到從AJAX調用發送到集成在Web API中的Message Handler的頭文件。請參閱圖像:Debugger screenshot無法從ASP.NET Web API中的jQuery AJAX請求中獲取標頭
下面是我的AJAX請求的代碼:
$.ajax({
url: "https://someservicename.azurewebsites.net/Service/RequestHandler",
beforeSend: function (xhr) {
xhr.setRequestHeader('Token', '86810e135958961ad4880ad');
},
type: "POST",
crossDomain: true,
data: {
param: "Passed Parameter"
},
success: function (msg) {
console.log(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
}
});
中的Web API的消息處理程序看起來象下面這樣:
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string authToken;
try
{
authToken = request.Headers.GetValues("Token").FirstOrDefault();
if (authToken != "86810e135958961ad4880ad")
{
return await Task.Factory.StartNew(() =>
{
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Unauthorized access!")
};
});
}
else
{
return await base.SendAsync(request, cancellationToken);
}
}
catch (System.InvalidOperationException)
{
return null;
}
}
當我從IIS中運行的代碼本地主機發送的請求如下所示:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:token
Access-Control-Request-Method:POST
Connection:keep-alive
Host:someservicename.azurewebsites.net
Origin:http://localhost:12522
Referer:http://localhost:12522/pocppd.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
而負責人我在控制檯上得到的是:
https://someservicename.azurewebsites.net/Service/RequestHandler. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:12522' is therefore not allowed access. The response had HTTP status code 500.
與POSTMAN客戶端請求工作正常,但從本地主機它會返回一個錯誤。請讓我知道沒有在我的消息處理程序中獲取標題的原因?
響應哪位會帶來幾十[結果](https://www.google.com.tr/search?q=Response+to+preflight+request+doesn %27噸+傳+訪問+對照+檢查%3A + NO +%27Access - 控制 - 允許來源%27&OQ =響應+至+預檢+請求+沒有按%27噸+傳+訪問+對照+檢查%3A + NO +%27Access -Control-Allow-Origin%27&aqs = chrome..69i57j69i59.119j0j7&sourceid = chrome&ie = UTF-8)在搜索時只是告訴你,服務器上不允許使用哪個請求的來源,因爲CORS標準。 Marius的回答是一種使服務器響應來自你本地主機的請求的方法。 – ibubi