I tried Digest authentication with RestSharp

1 minute read

background

I was looking around the HTTP client during Windows application development, but by default the HttpClient class is provided.
HttpClient class (System.Net.Http) | Microsoft Docs

However, this class seems to be quite a musician. (I don’t know because I haven’t actually used it)
When I looked it up on Qiita, it came out quite a bit, and I honestly thought that I didn’t want to use it.

Do not enclose HttpClient in using-Qiita
Caution is required when handling HttpClient of .NET (Framework) –Qiita

After further investigation, I found out that there is a REST API client library called RestSharp, and I thought it would be good, so I decided to try it with Digest authentication.

Introduction method

Install the following packages from NuGet Package Management.

  • RestSharp
  • RestSharp.Authenticators.Digest
  • RestSharp.Serializers.Utf8Json
Install-Package RestSharp
Install-Package RestSharp.Authenticators.Digest
Install-Package RestSharp.Serializers.Utf8Json

How to use

For example, suppose the API is a GET method and returns the following JSON data as a response.

{"foo": "bar", "baz": {"foo": "bar", "baz": "qux"}}

First, create a data class to receive JSON data.

Foo.cs


public class Foo
{
    public string foo { get; set; }

    public Baz baz { get; set; }
}

Baz.cs


public class Baz
{
    public string foo { get; set; }

    public string baz { get; set; }
}

Then, deserialize the JSON data from the request & response as shown below.

//Generate client (Set BaseURL)
var client = new RestClient("https://hogehoge.api/1.1)
{
    //Digest authentication settings
    Authenticator = new DigestAuthenticator("username", "password");
};

//JSON serializer settings (Utf8Json is used this time)
client.UseUtf8Json();

//Request generation (set resource and response data format)
var request = new RestRequest("foobaz", DataFormat.Json);

//Synchronous call
var response = client.Get(request);

//Deserialize JSON data
var result = new Utf8JsonSerializer().Deserialize<Foo>(response);

Roughly speaking, you can create an instance of the RestClient class, set the authentication method and JSON serializer, and pass the instance of the RestRequest class to the argument of the client.Get method.
Then, since the variable response contains the result, the JSON data is deserialized.

You can also make deserializations together by making asynchronous calls as follows.

//Asynchronous call (result returns as Foo type)
var result = await client.GetAsync<Foo>(request);

Reference URL

-Basic usage of RestSharp –Qiita