marc_s
marc_s

Reputation: 755197

Calling a REST service keeps failing (with RESTSharp)

I'm trying to talk to a REST service, and with tools like Postman or Fiddler, I'm getting the expected results just fine.

Now I'm trying to do the same from my C# code, using RestSharp 104.4.

I set up my REST client and define the user agent string, and the default Content-Type and Accept headers:

_restClient = new RestClient();
_restClient.UserAgent = CreateUserAgentString();
_restClient.AddDefaultHeader("Content-Type", "application/json");
_restClient.AddDefaultHeader("Accept", "application/json");

Then I'm trying to call a method called /token to get a security token, based on HTTP Basic Auth:

RestRequest request = new RestRequest(_baseServiceUrl + GetTokenUrl, Method.POST);
request.RequestFormat = DataFormat.Json;

request.AddHeader("Authorization", "Basic " + baseAuth);  // baseAuth contains the base Auth string
request.AddBody(request.JsonSerializer.Serialize(new { clientIdentifier = "Outlook", clientId = "52c600f6-262c-4fca-a4bc-e0e322e0571e" }));

My problem is: this resulting POST request always fails with an "internal server error":

Authorization: Basic .........
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: my defined user agent string
Content-Type: application/json
Host: dev.xxx.yyyyyyyy.ch
Content-Length: 90
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

Body:

"{\"clientIdentifier\":\"Outlook\",\"clientId\":\"52c600f6-262c-4fca-a4bc-e0e322e0571e\"}"

The problems are several:

Upvotes: 3

Views: 5980

Answers (1)

Margus
Margus

Reputation: 20058

Filling the missing link. Following should work:

_restClient = new RestClient();
_restClient.BaseUrl = url;

var request = new RestRequest(_baseServiceUrl + GetTokenUrl, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Basic " + baseAuth); 
request.AddBody(new {
    root = new { 
        clientIdentifier = "Outlook", 
        clientId = "52c600f6-262c-4fca-a4bc-e0e322e0571e" 
    }
});

I have used WebRequest for this in the past, I am sure, I wont be doing that again :D

Upvotes: 3

Related Questions