2017-04-02 80 views
0

的WebAPI我們有網頁API象下面這樣:發佈與ModelClass對象作爲參數

[HttpPost] 
public CustomAuthenticateModel AuthenticateByUsername(LoginModel model) 
{ 
    return employeeService.AuthenticateByUsername(model.Username, model.AdDomain, model.IsAdAuthentication); 
} 

在我的PCL項目我想通過訪問:

try 
{ 
    HttpResponseMessage response = null; 
    LoginModel l = new LoginModel(); 
    l.Username = model.Email; 
    response = await apiClient.PostAsJsonAsync(uri, l); // Exception is fired at this line 
} 
catch(exception etc){} 

,每次我得到異常例如:

ex = {System.TypeInitializationException:'System.Net.Http.FormattingUtilities'的類型初始值設定項引發異常。 ---> System.NotImplementedException:該方法或操作未實現。 在System.Runtime.Serialization.XsdDataContractExporte ...

這是現有的項目,所有的API消耗模型類對象作爲參數。什麼是正確的方式來做到這一點?我正在嘗試爲此項目使用MVVM輔助程序庫。

+0

你的apiClient是什麼?您是否使用此庫 –

+0

我遇到了同樣的問題。你找到解決方案嗎? – nishantvodoo

回答

0

在發出請求之前序列化您的對象。 Javascript串行器應該像Newtonsoft串行器一樣工作

var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(argument); 
var content = new StringContent(jsonRequest, Encoding.UTF8, "text/json"); 

//url is the api, l is your object that you are passing 
var response = await client.PostAsync(url, l); 

if (response.IsSuccessStatusCode) 
{ 
    //R is your object type, in this case LoginModel 
    result = Newtonsoft.Json.JsonConvert.DeserializeObject<R>(await response.Content.ReadAsStringAsync()); 
}