将请求标头添加到jquery ajax调用会抛出101异常

时间:2013-03-11 11:42:22

标签: jquery ajax wcf rest header

您好我已经尽可能地简化了我的代码。我想要实现的是调用一个宁静的wcf服务。但是当我添加set request header方法时,我在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控制台窗口中没有错误。

[object Object] 错误 [例外......“失败”nsresult:“0x80004005(NS_ERROR_FAILURE)”位置:“JS frame :: http://code.jquery.com/jquery-1.9.1.min.js :: .send :: line 5”data:no]

2 个答案:

答案 0 :(得分:0)

请你看看at this stackoverflow question,我认为它证明了你想要实现的目标。

我认为你将一个参数传递给setRequestHeader太多了。

答案 1 :(得分:0)

我终于发现了我的代码问题,原因是授权标头不允许服务器端。所以为了解决这个问题,我需要在wcf项目的global.asac.cs类中添加一些代码。以下代码还支持跨域调用。

    protected void Application_BeginRequest(object sender, EventArgs e)
    {

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();

        EnableCrossDmainAjaxCall();
    }

    private void EnableCrossDmainAjaxCall()
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
                      "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                          "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                          "Content-Type, Accept, Authorization");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
                          "1728000");
            HttpContext.Current.Response.End();
        }
    }

感谢Nikolaos的帮助。