2017-04-02 78 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()); 
}