[c#] RestSharp JSON Parameter Posting

I am trying to make a very basic REST call to my MVC 3 API and the parameters I pass in are not binding to the action method.

Client

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);

Server

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
}

Am I missing something here?

This question is related to c# json asp.net-mvc-3 rest restsharp

The answer is


This is what worked for me, for my case it was a post for login request :

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  

body :

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

Here is complete console working application code. Please install RestSharp package.

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.
    }
  }
}

Hope this will help someone. It worked for me -

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;

In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:

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

This method sets content type to application/json and serializes the object to a JSON string.


You might need to Deserialize your anonymous JSON type from the request body.

var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);

If you have a List of objects, you can serialize them to JSON as follow:

List<MyObjectClass> listOfObjects = new List<MyObjectClass>();

And then use addParameter:

requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));

And you wil need to set the request format to JSON:

requestREST.RequestFormat = DataFormat.Json;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to restsharp

How do I get an OAuth 2.0 authentication token in C# Converting a JToken (or string) to a given Type How to POST request using RestSharp RestSharp simple complete example RestSharp JSON Parameter Posting