我正在尝试使用 ajax 调用 wcf 函数,如下所示:
$.ajax({
url:http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?',
dataType: 'json',
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "BasicAuthTest");
},
success: function(trackingData) {
alert("success");
}
});
WCF 代码正在鸣叫并正在接收请求
public class CustomUserNameValidatorBasic : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
try
{
var msg = operationContext.RequestContext.RequestMessage;
// If user requests standart help-page then ignore authentication check.
if (msg.Properties.ContainsKey("HttpOperationName") && msg.Properties["HttpOperationName"].ToString() == "HelpPageInvoke")
{
return base.CheckAccessCore(operationContext);
}
var httpRequestHeaders = ((HttpRequestMessageProperty) msg.Properties[HttpRequestMessageProperty.Name]).Headers;
// Is Authorization-header contained in http-headers?
if (!httpRequestHeaders.AllKeys.Contains(HttpRequestHeader.Authorization.ToString()))
{
//code returns here
return false;
}
return false;
}
catch (Exception e)
{
return false;
}
}
}
如图所示,“授权”标头不包含在 req 标头数组中
在 ajax reqeuest 的请求标头下的 Firebug 中:
Request Headersview source Accept / Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5 Cache-Control max-age=0
Connection keep-alive Host test.proxyU.com If-Modified-Since Wed, 21 Mar 2012 19:46:56 GMT If-None-Match "e0818-17278-4bbc60dc86c00"
用户代理 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0)
Gecko/20100101 Firefox/16.0
更新:考虑到下面的答案,我尝试了以下 3 种方法,它们都没有添加标题。所有人都正确调用 wcf,但“授权”标头不在请求中。如果我查看 http 请求,标题看起来非常像我在上面发布的屏幕截图
方法一
$.ajax({
url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
beforeSend: function(xhr){xhr.setRequestHeader("Authorization", "BasicAuthTest");},
success: function(trackingData) {
alert("success");
}
});
方法二
$.ajax({
url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
headers: {"Authorization": "BasicAuthTest"},
success: function(trackingData) {
alert("success");
}
});
方法三
$.ajax({
url: "http://localhost:64121/Test.svc/json/GetNumber?X='+ var1 + '&callback=?'",
beforeSend : function(xhr, settings) {
$.extend(settings, { headers : { "Authorization" : "BasicAuthTest" } });
},
success: function(trackingData) {
alert("success");
}
});