1

嗨,我在下面尽可能地简化了我的代码。我想要实现的是调用一个宁静的 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 行“数据:无]

4

2 回答 2

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();
        }
    }

感谢尼古拉斯的帮助。

于 2013-03-12T14:09:15.953 回答
0

你能看看这个stackoverflow问题吗,我认为它展示了你想要实现的目标。

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

于 2013-03-11T11:54:41.813 回答