2013-03-11 129 views
1

嗨,我儘可能簡化了我的代碼。我試圖實現的是調用一個restful的wcf服務。但是,當我添加設置請求標頭方法時,我在Firefox和Chrome中都遇到了異常,但它在IE中起作用,它成功地訪問了服務方法。將請求頭添加到jquery ajax調用拋出101異常

<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」 的數據:無]

回答

0

你可以看看at this stackoverflow question,我認爲它展示了你想要達到的目標。

我想你傳遞一個參數太多setRequestHeader。

+0

嗨,不幸的是刪除setRequestHeader方法的第二個或第三個參數產生相同的錯誤。 – Mark 2013-03-11 12:35:58

+0

您是否可以通過其他方式成功撥打服務,例如:通過一個小的C#控制檯應用程序?所以你可以消除任何其他問題,如錯誤的鹽或類似的小問題。 – 2013-03-11 13:23:54

+0

嗨尼古拉斯,是的,我可以通過c#控制檯應用程序調用服務。我可以給你發送示例代碼。我有通過c#console應用程序調用並通過web應用程序調用的寧靜服務。如果我刪除設置標題方法,它工作正常。對於這個問題,我在網上找不到任何幫助。 – Mark 2013-03-11 14:19:29

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

感謝尼古拉斯的幫助。

+0

乾杯,很高興你解決了它! – 2013-03-13 09:00:21