RestSharp JSON Parameter Posting
我正在尝试对MVC 3 API进行非常基本的REST调用,并且传入的参数未绑定到action方法。
客户端
1 2 3 4 5 6 7 8 9 |
服务器
1 2 3 4 5 6 7 8 9 10 11 | 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 } |
我在这里想念什么吗?
您不必自己序列化身体。只要做
1 2 | request.RequestFormat = DataFormat.Json; request.AddJsonBody(new { A ="foo", B ="bar" }); // Anonymous type object is converted to Json body |
如果您只想使用POST参数(它仍将映射到您的模型,并且由于没有序列化到JSON而效率更高),请执行以下操作:
1 2 | request.AddParameter("A","foo"); request.AddParameter("B","bar"); |
在当前版本的RestSharp(105.2.3.0)中,您可以使用以下命令将JSON对象添加到请求正文中:
1 |
此方法将内容类型设置为application / json并将对象序列化为JSON字符串。
这对我有用,对我而言,这是一个登录请求的帖子:
1 2 3 4 5 6 7 8 9 10 | 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 |
身体:
1 2 3 4 |
希望这会帮助某人。对我有用-
1 2 3 4 5 6 7 8 9 10 11 12 | RestClient client = new RestClient("http://www.example.com/"); RestRequest request = new RestRequest("login", Method.POST); request.AddHeader("Accept","application/json"); var body = new { Host ="host_environment", Username ="UserID", Password ="Password" }; request.AddJsonBody(body); var response = client.Execute(request).Content; |
您可能需要从请求正文中反序列化您的匿名JSON类型。
1 2 | var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result; ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody); |
如果您有对象的
1 |
然后使用
1 | requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects)); |
您将需要将请求格式设置为
1 | requestREST.RequestFormat = DataFormat.Json; |
这是完整的控制台工作应用程序代码。请安装RestSharp软件包。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using RestSharp; using System; namespace RESTSharpClient { class Program { static void Main(string[] args) { string url ="https://abc.example.com/"; string jsonString ="{" + ""auth": {" + ""type" : "basic"," + ""password": "@P&p@y_10364"," + ""username": "prop_apiuser"" + "}," + ""requestId" : 15," + ""method": {" + ""name": "getProperties"," + ""params": {" + ""showAllStatus" : "0"" + "}" + "}" + "}"; IRestClient client = new RestClient(url); IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json); request.AddHeader("Content-Type","application/json; CHARSET=UTF-8"); request.AddJsonBody(jsonString); var response = client.Execute(request); Console.WriteLine(response.Content); //TODO: do what you want to do with response. } } } |