Home > OS >  Access a REST API with C#
Access a REST API with C#

Time:07-18

I try to access to the REST API from NetExplorer. It works when I send a request with postman :

enter image description here

But It doesn't with my C# code :

var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");

        var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };

        JsonResult result = new JsonResult(ReqAuth);
        
        var request = new RestRequest(result.ToString(), Method.Post);
        
        request.AddHeader("Accept", "application/json");
        
        RestResponse response = await client.ExecuteAsync(request);

Here's the error message :

{"error":"Il n'existe aucune m\u00e9thode de l'API pouvant r\u00e9pondre \u00e0 votre appel."}

In english, there's no API method to resolve your call

If somebody can help me ...

Thanks

CodePudding user response:

You are using the constructor of RestRequest wrong, the constructor does not take in the content (body) like that. Try using it with AddJsonBody like so:

var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
 
var request = new RestRequest();
request.Method = RestSharp.Method.Post;
request.AddJsonBody(ReqAuth);
    
request.AddHeader("Accept", "application/json");
    
RestResponse response = await client.ExecuteAsync(request);

Documentation: https://restsharp.dev/usage.html#request-body

  • Related