41

I m trying to POST the request using RestSharp client as follows I m passing the Auth Code to following function

public void ExchangeCodeForToken(string code)
{
    if (string.IsNullOrEmpty(code))
    {
        OnAuthenticationFailed();
    }
    else
    {           
        var request = new RestRequest(this.TokenEndPoint, Method.POST);
        request.AddParameter("code", code);
        request.AddParameter("client_id", this.ClientId);
        request.AddParameter("client_secret", this.Secret);
        request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
        request.AddParameter("grant_type", "authorization_code");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");

        client.ExecuteAsync<AuthResult>(request, GetAccessToken);
    }
}

void GetAccessToken(IRestResponse<AuthResult> response)
{
    if (response == null || response.StatusCode != HttpStatusCode.OK
                         || response.Data == null 
                         || string.IsNullOrEmpty(response.Data.access_token))
    {
        OnAuthenticationFailed();
    }
    else
    {
        Debug.Assert(response.Data != null);
        AuthResult = response.Data;
        OnAuthenticated();
    }
}

But i am getting response.StatusCode = Bad Request. Can anyone help me for how do i POST the request using Restsharp client.

Xaruth
  • 3,968
  • 3
  • 17
  • 24
Ashish
  • 743
  • 2
  • 8
  • 16

5 Answers5

66

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

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

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}
Sam
  • 6,961
  • 15
  • 44
  • 63
David
  • 1,559
  • 10
  • 21
16

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

Kutyel
  • 6,297
  • 2
  • 26
  • 55
8

As of 2017 I post to a rest service and getting the results from it like that:

        var loginModel = new LoginModel();
        loginModel.DatabaseName = "TestDB";
        loginModel.UserGroupCode = "G1";
        loginModel.UserName = "test1";
        loginModel.Password = "123";

        var client = new RestClient(BaseUrl);

        var request = new RestRequest("/Connect?", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(loginModel);

        var response = client.Execute(request);

        var obj = JObject.Parse(response.Content);

        LoginResult result = new LoginResult
        {
            Status = obj["Status"].ToString(),
            Authority = response.ResponseUri.Authority,
            SessionID = obj["SessionID"].ToString()
        };
Recev Yildiz
  • 721
  • 9
  • 9
  • 2
    As of now/5/28/2019 you would use AddJsonBody instead of AddBody since you have chosen DataFormat.Json instead of XML. This does both object to JSON and adding to the body of the request in one statement. – Chris May 28 '19 at 14:30
2

it is better to use json after post your resuest like below

  var clien = new RestClient("https://smple.com/");
  var request = new RestRequest("index", Method.POST);
  request.AddHeader("Sign", signinstance);    
  request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
  var response = client.Execute<YourReturnclassSample>(request);
  if (response.StatusCode == System.Net.HttpStatusCode.Created)
   {
       return Ok(response.Content);
   }
0

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }