2011-06-10 94 views
97

我正在嘗試對我的MVC 3 API進行非常基本的REST調用,並且我傳入的參數沒有綁定到操作方法。RestSharp JSON參數發佈

客戶

var request = new RestRequest(Method.POST); 

request.Resource = "Api/Score"; 
request.RequestFormat = DataFormat.Json; 

request.AddBody(request.JsonSerializer.Serialize(new { A = "foo", B = "bar" })); 

RestResponse response = client.Execute(request); 
Console.WriteLine(response.Content); 

服務器

public class ScoreInputModel 
{ 
    public string A { get; set; } 
    public string B { get; set; } 
} 

// Api/Score 
public JsonResult Score(ScoreInputModel input) 
{ 
    // input.A and input.B are empty when called with RestSharp 
} 

我失去了一些東西在這裏?

回答

157

你不必親自序列化身體。只要做到

request.RequestFormat = DataFormat.Json; 
request.AddBody(new { A = "foo", B = "bar" }); // uses JsonSerializer 

如果你只是想post數據,而不是(這將仍然映射到你的模型,是很多更有效,因爲沒有序列化JSON)做到這一點:

request.AddParameter("A", "foo"); 
request.AddParameter("B", "bar"); 
+0

這樣做了!謝謝約翰! – 2011-06-10 23:41:17

+0

哪一個工作? – 2011-06-11 00:04:54

+4

兩者。然而,第二種方法要快得多。 – 2011-06-11 00:32:35

20

這是什麼爲我工作,我的情況它是爲登錄請求後:

var client = new RestClient("http://www.example.com/1/2"); 
var request = new RestRequest(); 

request.Method = Method.POST; 
request.AddHeader("Accept", "application/json"); 
request.Parameters.Clear(); 
request.AddParameter("application/json", body , ParameterType.RequestBody); 

var response = client.Execute(request); 
var content = response.Content; // raw content as string 

體:

{ 
    "userId":"[email protected]" , 
    "password":"welcome" 
} 
19

RestSharp的當前版本(105.2.3.0),則可以JSON對象添加到請求體:

request.AddJsonBody(new { A = "foo", B = "bar" }); 

此方法設置內容類型爲application/JSON和序列化對象的JSON串。

+0

如何將文件附加到此請求中? – OPV 2017-07-23 19:49:57

+0

如何命名對象?例如,如果您需要發送「詳細信息」: {「extra」:「stuff」}? – mdegges 2018-02-08 00:50:09

+0

@OPV您可以像下面這樣向請求添加一個文件:request.AddFile(pathToTheFile); – 2018-02-09 01:31:49