2014-02-14 141 views
1

我正在測試用ASP.NET Web API編寫RESTful API。我在客戶端上使用RestSharp來模擬不同的調用。Rest Rest API調用ASP.NET Web API

我想提交一個應用程序ID查詢字符串,並且正文應該是一個類型爲「Log」的集合。每次,由服務器接收的正文發佈的應用程序ID get始終爲NULL。

代碼在服務器上:

public class LogsController : ApiController 
{ 
    public HttpStatusCode Post(Guid ID, [FromBody] List<Log> logs) 
    { 
     if (logs != null) 
      return HttpStatusCode.OK; 
     else 
      return HttpStatusCode.PreconditionFailed; 
    } 
} 

public class Log 
{ 
    public Guid ErrorId { get; set; } 
} 

在客戶端代碼:

static void Main(string[] args) 
    { 
     var client = new RestClient("http://localhost:36146/api"); 

     var json = JsonConvert.SerializeObject(new List<Log>() 
      { 
       new Log { ErrorId = Guid.NewGuid()} 
      }); 

     var request = new RestRequest("Logs", Method.POST); 

     request.RequestFormat = DataFormat.Json; 
     request.AddParameter("ID", Guid.NewGuid(), ParameterType.QueryString); 
     request.AddHeader("Accept", "application/json"); 
     request.AddHeader("Content-Type", "application/json; charset=utf-8"); 
     request.AddBody(json); 

     IRestResponse response = client.Execute(request); 
     Console.WriteLine(response.Content); 
     Console.Read(); 
    } 

    public class Log 
    { 
     public Guid ErrorId { get; set; } 
    } 

我想我得到了這個工作,但是不管是什麼我現在做的「日誌」參數在服務器上始終爲NULL。

+0

保羅 - 它很好的知道你找到了解決方案,這裏是一個鏈接:http://www.codeproject.com/Articles/826359/Consuming-ASP-NET-WEB-API-using-ASP-NET-MVC描述RestSharp用法的 - 和 - Re可能會有所幫助。 –

回答

1

我想我找到了問題。

RestSharp在填充請求的主體時隱式使用JsonSerializer。因爲我也被稱爲序列化程序,我認爲它導致格式問題。

我已經將該調用移除到序列化程序,現在我正從服務器接收一個200。

快樂的日子。

+0

你可以使用這個庫切換到使用Json.NET - https://www.nuget.org/packages/RestSharp.Newtonsoft.Json – Adam