consume API , sending json username and password using POST using Restsharp in C# Console application

234 views
Skip to first unread message

George Wadie

unread,
Jan 8, 2023, 2:27:32 PM1/8/23
to RestSharp
Dears, 

i am trying to Consume the API  
so i can get token 

i should send the following json in the Body 
{

"username":"admin",
"password":"admin"

}


and  in Headers  Content-Type : application/json  

actually it works in Postman and i get the token   in the response , but when trying to test the same using Restsharp in C#    as below  i got error :  
//Exception thrown: 'System.Net.WebException' in System.dll 
//also the response.StatusCode show not found when tracing the error 

 public static void BioTimegetJWT()
        {
               
            var client = new RestClient("http://biotimedxb.com:8085/");
            var request = new RestRequest("jwt-api-token-auth", Method.POST);

           
           
            //1-Add Header
              request.AddHeader("Content-Type", "application/json");

            
            request.AddBody("username", "admin");
            request.AddBody("password","admin");

           
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string rawResponse = response.Content;
                Console.WriteLine(rawResponse);

                //this creates the mappping between the outcoming data and the class rootobject
                //or Deserialize the Object
                //Rootobject result = JsonConvert.DeserializeObject<Rootobject>(rawResponse);
            }

        }

Alexey Zimarev

unread,
Jan 9, 2023, 3:55:18 AM1/9/23
to RestSharp
class GetToken {
  string Username {get;set;}
  string Password {get;set;}
}

var request = new RestRequest("jwt-api-token-auth", Method.Post); // v108+
request.AddJsonBody(new GetToken { ... });
var response = await client.PostAsync<Rootobject>(request);

It's all in the docs. I suggest reading the documentation.

George Wadie

unread,
Jan 10, 2023, 9:12:23 PM1/10/23
to RestSharp
thank you for the  reply i will check the documentation
Reply all
Reply to author
Forward
0 new messages