我試圖實現一個跨域請求,並失敗悲慘。我正在嘗試使用最新版本的Firefox,Chrome和IE10。我在所有瀏覽器中都獲得了相同的體驗。我試圖設置驗證標頭或自定義標題鍵/值對,以便我可以在我的服務器上獲取值。我使用的是jQuery 2.03。jQuery ajax頭沒有設置
$.ajax({
type: "GET",
beforeSend: function (xhr, settings)
{
$.extend(settings, { headers: { "Authorization": "121212" } });
},
url: url,
dataType: "json",
processData: false,
crossDomain: true,
success: function (msg)
{
alert('it works!!!');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("error dude: " + JSON.stringify(jqXHR));
}
});
服務器上的授權標頭值爲空。我嘗試用自定義密鑰替換授權,但它沒有設置。我嘗試添加這Ajax調用:
headers: { Authorization: "fooooo" },
但這樣做的結果Ajax調用從未到達服務器。當我向ajax調用添加標題:屬性時,我的斷點永遠不會到達。但是,如果我放棄這一點,那麼我的斷點就會被擊中。
我正在調用ASP.Net MVC WebApi控制器。我創建攔截請求並獲取授權值,所以我可以爲他們的旅行對用戶進行認證,以我的WebAPI處理程序:
public class AuthorizationHeaderHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync
(
HttpRequestMessage request,
CancellationToken cancellationToken
)
{
IEnumerable<string> apiKeyHeaderValues;
if (request.Headers.TryGetValues("Authorization", out apiKeyHeaderValues))
{
var apiKeyHeaderValue = apiKeyHeaderValues.First();
var user = SecurityRepository.GetUserByUserKey(apiKeyHeaderValue);
IList<Claim> claimList = new List<Claim>();
claimList.Add(new Claim(ClaimTypes.Name, user.Name));
claimList.Add(new Claim(GALClaimTypes.UserKey, user.UserKey.ToString(CultureInfo.InvariantCulture)));
claimList.Add(new Claim(GALClaimTypes.AuthenticationId, user.AuthenticationId.ToString(CultureInfo.InvariantCulture)));
claimList.Add(new Claim(GALClaimTypes.PersonId, user.PersonId.ToString(CultureInfo.InvariantCulture)));
claimList.Add(user.EmailAddress != null
? new Claim(ClaimTypes.Email, user.EmailAddress)
: new Claim(ClaimTypes.Email, "unknown"));
var identity = new ClaimsIdentity(claimList, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
}
return base.SendAsync(request, cancellationToken);
}
}
此代碼永遠不會觸發因爲授權不能設置。我錯過了什麼。我已經閱讀了很多似乎使用我的方法的帖子,似乎對他們有用。任何見解都非常感謝。謝謝你的幫助。
您是否嘗試過使用'headers'屬性,而不是在'beforeSend'設置呢? – CodingIntrigue