Calling a REST Service with Basic Authentication from C#

I was recently tasked with calling a REST service using Basic Authentication.

I was not sure how to do it but I found that it was really easy to do using the RestSharp library.

In order to use BasicAuthentication you just need to use the HttpBasicAuthenticator class.

var userName = "myuser";
var password = "mypassword";
var host = "";
var client = new RestClient("https://" + host + "/method1");            client.Authenticator = new HttpBasicAuthenticator(userName, password);            var request = new RestRequest(Method.POST);            request.AddHeader("Accept", "application/json");            request.AddHeader("Cache-Control", "no-cache");            request.AddHeader("Content-Type", "application/json");            request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Example of calling a REST service passing user and password for BasicAuthentication

And that's all. As you can see pretty easy!