我试图实现一个跨域请求,并失败悲惨。我正在尝试使用最新版本的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