2014-07-23 62 views
0

我想讓我的ajax調用工作來連接到使用ServiceStack的API。我遇到的問題是身份驗證。在C#我做的呼叫是這樣的:ServiceStack + Ajax身份驗證呼叫

string json = ""; 
    JsonServiceClient client; 
    client = new JsonServiceClient("https://api.domain.com"); 
          client.SetCredentials("test", "test"); 
          client.AlwaysSendBasicAuthHeader = true; 

    try 
    { 
    List<AppleResponse> response = client.Get<List<AppleResponse>>("/v1/getdata?id=1"); 
    json = response.ToJson(); 
    } 
    catch (Exception ex) 
    { 
    json = ex.Message; 
    } 

    JArray v = JArray.Parse(json); 
    var total = v[0]["total"].ToString(); 

我得到的總的價值,例如總= 10 現在我想做的使用Ajax調用同樣的事情。這裏是未經驗證即可調用示例:

 function Getdata(id) { 
      $.ajax({ 
       url: '//api.domain.com/v1/getdata', 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       data: JSON.stringify({ id_s: id }), 
       success: function (f) { 
        $.each(f.d, function (i, e) { 
         alert(e.total); 
        }); 
       }, 
       cache: false 
      }); 
     } 

有誰知道我怎麼能加入身份驗證,但不顯示在JavaScript標記中的用戶名/密碼?非常感謝。

+0

可以保存在頭的身份驗證令牌,並將其發送的每當你做阿賈克斯呼叫。 – reptildarat

+0

謝謝reptildarat,你知道確切的語法嗎?像這樣:$ .ajax({url:'//api.domain.com/v1/getdata', type:「POST」, contentType:「application/json; charset = utf-8」,auth :<%= client %>,數據:... – carol1287

回答

4

那麼,因爲您使用基本身份驗證,所以沒有辦法不透露您的用戶名或密碼。但你可以把它像這樣工作的:

function Getdata(id) { 
    $.ajax({ 
     url: '//api.domain.com/v1/getdata', 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     data: JSON.stringify({ id_s: id }), 
     beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); 
     }; 
     success: function (f) { 
      $.each(f.d, function (i, e) { 
       alert(e.total); 
      }); 
     }, 
     cache: false 
    }); 
} 

但是,如果你不希望透露自己的用戶名或密碼呢,你需要建立一個接受你的自定義頁眉自己的身份驗證過濾器。

你可以看到如何在此:Servicestack wiki

然後你就可以保存您的身份驗證令牌,並將其發送這樣的:

function Getdata(id) { 
    $.ajax({ 
     url: '//api.domain.com/v1/getdata', 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     data: JSON.stringify({ id_s: id }), 
     headers: { 'my-auth-header': 'myToken' }, 
     success: function (f) { 
      $.each(f.d, function (i, e) { 
       alert(e.total); 
      }); 
     }, 
     cache: false 
    }); 
} 
+0

非常感謝你reptildarat – carol1287

相關問題