简体   繁体   中英

Access a REST API with C#

["

I try to access to the REST API from NetExplorer.<\/i>

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM