Home > OS >  RestSharp version > 107: How to implement NtlmAuthenticator?
RestSharp version > 107: How to implement NtlmAuthenticator?

Time:06-14

I got a source code from a colleague in which using RestSharp (version 106.15.0) in VB.NET retrieves data from a web api. I updated the RestSharp version to 108.0.1 and the code no longer works. I found out that some things have changed with RestSharp version 107. But I can't get the code to work anymore.

Old Code:

Dim restClient As New RestClient(server) With {
            .Timeout = 10000,
            .Authenticator = New NtlmAuthenticator(),
            .ThrowOnAnyError = True
        }
Dim response As IRestResponse
Dim restRequest = New RestRequest(sQ, Method.Post)
restRequest.AddHeader("content-type", "application/json")
restRequest.AddHeader(Settings.Default.AppIdKey, Settings.Default.AppIdValue)
restRequest.AddHeader("Accept-Language", "en")

How do I change this code to make it work again? I read that NtlmAuthenticator is now defined via ClientOptions with UseDefaultCredentials = true, but it doesn't work.

My approach so far:

Dim uri As New Uri("url")
Dim restClientOptions As RestClientOptions = New RestClientOptions(uri)
restClientOptions.UseDefaultCredentials = True
restClientOptions.ThrowOnAnyError = True
Dim restClient = New RestClient(restClientOptions)

When running the line Dim restClient = New RestClient(restClientOptions), a non-specific error is thrown.

CodePudding user response:

I created a very simple console application in both VB.NET and C#.NET with NtlmAuthenticator and was able to get the code to work with Restsharp > v107.

VB.NET:

Dim clientOptions As New RestClientOptions(BaseUrl) With
        {
            .UseDefaultCredentials = True
        }

        Using client As New RestClient(clientOptions)
            Dim request As New RestRequest(sQ, Method.Post)
            request.AddJsonBody(payload)
            Dim response As RestResponse = Await client.PostAsync(request)

            If response.IsSuccessful Then
                MsgBox(response.Content)
            End If
        End Using

C#.NET

RestClientOptions clientOptions = new RestClientOptions(BaseUrl)
                {
                    UseDefaultCredentials = true
                };

                using (RestClient client = new RestClient(clientOptions))
                {
                    string sQ = "...";
                    RestRequest request = new RestRequest(sQ, Method.Post);
                    request.AddJsonBody("JSON-Body");
                    RestResponse response = await client.PostAsync(request);
                    if (response.IsSuccessful)
                    {
                        Console.WriteLine(response.Content);
                    }
                }
  • Related