c-sharp

Send http post request with data in C# using restsharp

using RestSharp;
using System.Net;

public class RequestSender {
    public void UpdateFileStatus() {
        var client = new RestClient("http://your-api/base/url");

        var request = new RestRequest("/create/user", Method.POST);
        request.AddParameter("application/json", "{\"firstname\":\"hello\", \"lastname\":\"world\"}", ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        try {
            client.ExecuteAsync(request, response => 
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //DO Something with response.Content
                }
                else {
                    //Error occured in api
                }
            });
        }
        catch(Exception ex) {
            //Exception occured
        }
    }
}

Restsharp is a .Net package that can be used to make http requests with the server in C#. It can send all type of requests like GET, POST, PUT, DELETE, etc. You can also send data along with request using  restsharp.

In the code snippet, we have sent a post request to the server which is taking firstname and lastname as data and we are adding these using .AddParameter method of RestRequest.

Was this helpful?