Search code examples
c#restsharp

Restsharp Throws generic error messages compared to postman


when I use postman and enter incomplete MD hash it correctly shows an error that something is wrong with MD hash: Postman

But when I try to do the same in C# using Restsharp, I always get generic error message "Request failed with status code BadRequest". if I'm entering wrong Database name or wrong password or username, I only get that one error message. Meanwhile I get exact message in postman.

C# code:

using RestSharp;

var client = new RestClient("URL");
var request = new RestRequest();

//request.AddBody("Grant_type=password&Scope=Innovator&Client_id=IOMApp&Username=vipul&Password=21c603dbf852f78063f98674640ab339&Database=DATABASENAME");

//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddParameter("Grant_type", "password");
//request.AddParameter("Scope", "Innovator");
//request.AddParameter("Client_id", "IOMApp");
//request.AddParameter("Username", "vipul");
//request.AddParameter("Password", "21c603dbf852f78063f98674640ab33");
//request.AddParameter("Database", "DATABASENAME");

request.AddObject (new
{
    Grant_type = "password",
    Scope = "Innovator",
    Client_id = "IOMApp",
    Username = "vipul",
    Password = "21c603dbf852f78063f98674640ab33",
    Database = "DATABASENAME"
});

var response = client.Post(request);

C# Output when I use Wrong MD Hash

System.Net.Http.HttpRequestException
  HResult=0x80131500
  Message=Request failed with status code BadRequest
  Source=RestSharp
  StackTrace:
   at RestSharp.RestClientExtensions.<PostAsync>d__18.MoveNext()
   at RestSharp.AsyncHelpers.<>c__DisplayClass1_0`1.<<RunSync>b__0>d.MoveNext()
   at RestSharp.AsyncHelpers.CustomSynchronizationContext.<<Run>g__PostCallback|7_0>d.MoveNext()
   at RestSharp.AsyncHelpers.CustomSynchronizationContext.Run()
   at RestSharp.AsyncHelpers.RunSync(Func`1 task)
   at RestSharp.AsyncHelpers.RunSync[T](Func`1 task)
   at Program.<Main>$(String[] args) in C:\Users\201031703\source\repos\basic api\basic api\Program.cs:line 30

Request failed with status code BadRequest

Can someone please help me out with this?


Solution

  • I used

        var response = await client.PostAsync(uri, content);
        var result = await response.Content.ReadAsStringAsync();
    

    This fixed my problem, Instead of throwing an exception, I get a proper response in the variable.