【问题标题】:Adding request header to jquery ajax call throws 101 exception将请求标头添加到 jquery ajax 调用会引发 101 异常
【发布时间】:2013-03-11 11:42:21
【问题描述】:

您好,我在下面尽可能简化了我的代码。我想要实现的是调用一个安静的 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 frame :: http://code.jquery.com/jquery-1.9.1.min.js :: .send :: line 5”数据:否]

【问题讨论】:

    标签: jquery ajax wcf rest header


    【解决方案1】:

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

    我认为您向 setRequestHeader 传递的参数过多。

    【讨论】:

    • 嗨,不幸的是,删除 setRequestHeader 方法的第二个或第三个参数会产生相同的错误。
    • 能否通过其他方式成功调用服务,例如:通过一个小的 C# 控制台应用程序?因此,您可以消除任何其他问题,例如错误的盐或类似的琐碎问题。
    • 嗨 Nikolaos,是的,我可以通过 c# 控制台应用程序调用该服务。我可以向您发送示例代码。我有 c# 控制台应用程序和 Web 应用程序调用的 wcf restful 服务。如果我删除 set header 方法,它可以正常工作。我在网上找不到任何关于这件事的帮助。
    • 并且您在 C# 应用程序中以相同的方式生成授权标头?目标 URL 的 MD5 散列与密钥然后 base64 整个事情?您可以尝试的另一件事是使用 headers 属性,而不是使用 beforeSend 函数。查看第二个答案in this question
    • 您好,您有我可以发送的电子邮件吗?
    【解决方案2】:

    我终于找到了我的代码的问题,这是由于服务器端不允许授权标头。所以为了解决这个问题,我需要在我的 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 的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多