2016-04-29 67 views
0

我在Xamarin上使用RestSharp与WebAPI使用POST进行通信。我可以发送一些信息并得到回应,但结果并不符合我的预期。Xamarin RestSharp:将Json对象发送到Azure Web API并返回空结果

这是我在Xamarin上的代码。

   var request = new RestSharp.RestRequest ("api/device/stats", RestSharp.Method.POST); 
      request.AddHeader ("Content-Type", "application/json; charset=utf-8"); 

      request.RequestFormat = DataFormat.Json; 
      request.AddBody(new AppUsageInfo {MAC = "ASDF"}); 
      RestSharp.IRestResponse response = client.Execute (request); 
      var content = response.Content; 

在我的WebAPI:

public string Post([FromUri]UsageLogModel usageState) 
    { 
     //LogFunction.AddUsageLogs(usageState); 
     if (usageState.MAC == null) 
      return "fail"; 
     else 
      return "success"; 
    } 

UsageLogModel是:

public class UsageLogModel 
{ 
    public string MAC; 
} 

不知何故的响应是 “失败” 的MAC是空的。我抓了我的脑袋,但不知道发生了什么.-

+0

在其他请求中使用的类型'AppUsageInfo'is从你在你期待一个不同的POST方法'UsageLogModel' – Milen

回答

2

您的Xamarin代码将MAC内容放在请求的主体中(这可能适用于POST),但Web API预计参数在查询字符串中(这是[FromUri]属性的作用)。尝试更改Web API方法:

public string Post([FromBody]UsageLogModel usageState) 
+0

你是正确的。我应该已经阅读更多小心。 – LittleFunny