嗨,我在下面尽可能地简化了我的代码。我想要实现的是调用一个宁静的 wcf 服务。但是,当我添加设置请求标头方法时,我在 Firefox 和 chrome 中都得到了异常,但它在 IE 中工作,它成功地命中了服务方法。
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-md5.js"></script>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/enc-base64-min.js"></script>
<script type="text/javascript">
function WriteResponse(string) {
$("#divResult").val(string);
}
function setHeader(xhr) {
var secretkey = "1234dgt";
var hashedUrl = CryptoJS.HmacMD5($('#txtUrl').val(), secretkey);
var hashedUrlBase64 = hashedUrl.toString(CryptoJS.enc.Base64);
xhr.setRequestHeader('Authorization', hashedUrlBase64, "1234dgt");
}
$(document).ready(function () {
$("#btnCall").click(function () {
jQuery.support.cors = true;
$.ajax({
url: $('#txtUrl').val(),
type: 'GET',
async: false,
dataType: 'json',
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
},
beforeSend: setHeader
});
});
});
</script>
任何帮助将非常感激。
谢谢
// Here is the c# code used to call the same service:
public static string GetUserBookmarks(string uri)
{
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
string encodedUri = EncodeText(_key, uri, UTF8Encoding.UTF8);
request.Headers[HttpRequestHeader.Authorization] = encodedUri;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream bookmarksStream = response.GetResponseStream();
StreamReader reader = new StreamReader(bookmarksStream);
string str = reader.ReadToEnd();
reader.Close();
bookmarksStream.Close();
return str;
}
public static string EncodeText(string key, string text, Encoding encoding)
{
HMACMD5 hmacMD5 = new HMACMD5(encoding.GetBytes(key));
byte[] textBytes = encoding.GetBytes(text);
byte[] encodedTextBytes =
hmacMD5.ComputeHash(textBytes);
string encodedText =
Convert.ToBase64String(encodedTextBytes);
return encodedText;
}
// Here is the wcf service method and its interface\contract
[ServiceContract]
public interface IRestSerivce
{
[WebGet(UriTemplate = "users/{username}")]
[OperationContract]
List<string> GetUserBookmarks(string username);
}
public List<string> GetUserBookmarks(string username)
{
WebOperationContext context = WebOperationContext.Current;
OutgoingWebResponseContext outgoingResponseContext =
context.OutgoingResponse;
bool isUserAuthenticated = IsUserAuthenticated(username);
if (isUserAuthenticated == false)
{
outgoingResponseContext.StatusCode = HttpStatusCode.Unauthorized;
return null;
}
outgoingResponseContext.StatusCode = HttpStatusCode.OK;
List<string> bookmarks = new List<string>();
bookmarks.Add("User has been authenticated Successfully");
return bookmarks;
}
这是我收到的错误,这是产生此错误的 ajax 错误函数中的警报,但是 firbug 控制台窗口中没有错误。
[对象对象]错误[异常...“失败”nsresult:“0x80004005(NS_ERROR_FAILURE)”位置:“JS框架:: http ://code.jquery.com/jquery-1.9.1.min.js ::.发送 :: 第 5 行“数据:无]