RestSharp: Post Fails Using HttpClient in RestSharp Client constructor

While working with an API recently I encountered unexpected behavior when using an existing HttpClient in the RestClient constructor.

If I use the HttpClient in the constructor all my posts return with a bad request response (code 400), however creating the RestClient with the same base url as used in the HttpClient works.

To Reproduce

TestClass:

public class Connection {
    RestClient client;

    public Connection(bool wantFail)
    {
        string     baseUrl = @"https://travellermap.com/api/";
        HttpClient http    = new HttpClient();
        http.BaseAddress = new Uri(baseUrl);

        if (wantFail) {
            client = new RestClient(http);
        }
        else {
            client = new RestClient(baseUrl);
        }
    }

    public byte[] CreateSectorMapTest() {
        byte[] result;

       
        var request = new RestRequest("poster?subsector=A", Method.Post);
        request.AddHeader("Content-Type", "text/plain");
        request.AddHeader("Accept", "image/svg+xml");

        var body = @"#--------1---------2---------3---------4---------5-------
#PlanetName   Loc. UPP Code   B   Notes         Z  PBG Al
#----------   ---- ---------  - --------------- -  --- --
Cogrikonur    0101 C8C5446-9    Fl Ni              120 Im";

        request.AddParameter("text/plain", body, ParameterType.RequestBody);
        RestResponse response = client.Execute(request);

        if (response.IsSuccessful) {
            result = response.RawBytes;
        }
        else {
            result = null;
        }

        return result;
    }
}

Test Application Console:

Console.WriteLine("Hello, World!");

Console.WriteLine("Testing For Success");

Connection goodConnection = new Connection(false);
byte[] image = goodConnection.CreateSectorMapTest();

if (image != null) {
    Console.WriteLine("Good Connection Worked");
}
else {
    Console.WriteLine("Good Connection Failed");
}

Console.WriteLine("Testing For Fail");
Connection badConnection = new Connection(true);
byte[] imageBad = badConnection.CreateSectorMapTest();

if (imageBad != null) {
    Console.WriteLine("Bad Connection Worked");
}
else {
    Console.WriteLine("Bad Connection Failed");
}

Console.ReadLine();

Console.WriteLine("Finished");

Output of Console App: Hello, World! Testing For Success Good Connection Worked Testing For Fail Bad Connection Fail

Expected behavior

I would expect that the two constructors should provide the same functionality.

Desktop (please complete the following information):

  • OS: [e.g. Linux]
  • .NET version [e.g. .NET 6]
  • Version [e.g. 107.0.3.1-alpha.0.24] + in Clone of current repo

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

There’s an open issue to allow not to set the UserAgent by assigning null to the RestClientOptions.UserAgent. It’s impossible atm, but it will be fixed.

I had the same problem as described in the original question. In my case it turned out to be because the header “User-Agent” is not set by default in HttpClient whereas it turns out it is set by default by RestSharp. Setting this header on the HttpClient before passing it to the RestSharp constructor solved the problem for me, and it also made HttpClient work on its own.

The reason I started using RestSharp was because HttpClient failed. I then used RestSharp with a base address, but couldn’t sleep before I had figured out the reason why HttpClient failed. In my specific case I was trying to download an ics calendar file from https://outlook.office365.com/ The code I use is here: https://github.com/erlendthune/RememberCalendar

If a HttpClient is passed to the constructor and it does not have a base address set it results in:

System.ArgumentOutOfRangeException: Request resource doesn't contain a valid scheme for an empty base URL of the client (Parameter 'request')
   at RestSharp.RestClient.DoBuildUriValidations(RestRequest request) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/RestClient.cs:line 218
   at RestSharp.RestClient.BuildUri(RestRequest request) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/RestClient.cs:line 192
   at RestSharp.RestClient.ExecuteInternal(RestRequest request, CancellationToken cancellationToken) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/RestClient.Async.cs:line 57
   at RestSharp.RestClient.ExecuteAsync(RestRequest request, CancellationToken cancellationToken) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/RestClient.Async.cs:line 26
   at RestSharp.AsyncHelpers.<>c__DisplayClass1_0`1.<<RunSync>b__0>d.MoveNext() in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/AsyncHelpers.cs:line 47
--- End of stack trace from previous location ---
   at RestSharp.AsyncHelpers.CustomSynchronizationContext.<Run>g__PostCallback|7_0(Object _) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/AsyncHelpers.cs:line 84
   at RestSharp.AsyncHelpers.CustomSynchronizationContext.Run() in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/AsyncHelpers.cs:line 103
   at RestSharp.AsyncHelpers.RunSync(Func`1 task) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/AsyncHelpers.cs:line 32
   at RestSharp.AsyncHelpers.RunSync[T](Func`1 task) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/AsyncHelpers.cs:line 47
   at RestSharp.RestClient.Execute(RestRequest request) in /home/jordan/Code/DotNet/RestSharp/src/RestSharp/Sync/RestClient.Sync.cs:line 23
   at RestTest.Connection.CreateSectorMapTest() in /home/jordan/Code/DotNet/RestSharp/RestTest/Connection.cs:line 51

Also note as per my original message that the Base URL still has to be explicitly set even if the HttpClient base address is set or some posts cause a bad request issue. The following code has everything you need to test. I created a connection object as follows:

using RestSharp;

namespace RestTest;

/// <summary>
/// Test REST Client Connection
/// </summary>
public class Connection {
    RestClient client;

    public Connection(RestClient client) {

        this.client = client;
    }

    /// <summary>
    /// Test Post by getting an image from the API
    /// </summary>
    /// <returns>An image</returns>
    public byte[] CreateSectorMapTest() {
        byte[] result;

       
        var request = new RestRequest("/poster?subsector=A", Method.Post);
        request.AddHeader("Accept", "image/svg+xml");

        var body = @"#--------1---------2---------3---------4---------5-------
#PlanetName   Loc. UPP Code   B   Notes         Z  PBG Al
#----------   ---- ---------  - --------------- -  --- --
Cogrikonur    0101 C8C5446-9    Fl Ni              120 Im";

        request.AddStringBody(body, "text/plain");
        RestResponse response = client.Execute(request);

        if (response.IsSuccessful) {
            result = response.RawBytes;
        }
        else {
            result = null;
            Console.WriteLine($"RESPONSE STATUS: {response.StatusCode} : {response.StatusDescription}");
        }

        return result;
    }
}

A constructor that takes a REST Client and a single method that tries to get an image from the API I am working with.

This is the Console application I was using to try and find the source of the problem:

using RestSharp;
using RestTest;


string     baseUrl    = @"https://travellermap.com/api/";
HttpClient http       = new HttpClient();

// this code cause fatal exception
RestClient client     = new RestClient(http);
Connection connection = new Connection(client);
Console.WriteLine("Testing HTTPClient no base ADDRESS set");

try {
    connection.CreateSectorMapTest();
    Console.WriteLine("Success!");
}
catch (Exception e) {
    Console.WriteLine(e);
    
}

Console.WriteLine();
Console.WriteLine("Setting base address, Testing badRequest response");
http.BaseAddress = new Uri(baseUrl);

/// this code causes BadRequest reply
client     = new RestClient(http);
connection = new Connection(client);

byte[] image = connection.CreateSectorMapTest();

if (image != null) {
    Console.WriteLine("Request Succeeded");
}
else {
    Console.WriteLine("Request Failed.");
}

Console.WriteLine();
Console.WriteLine("Explicitly setting RestClient base URL, Testing for Success");

/// This code works NOTE - ONLY DIFFERENCE is this explicitly sets base URL for REST CLIENT
/// Note it is also the exact same URI used to set the base address of the HttpClient
client     = new RestClient(http,new RestClientOptions{BaseUrl = new Uri(baseUrl)});
connection = new Connection(client);
image = connection.CreateSectorMapTest();

if (image != null) {
    Console.WriteLine("Request Succeeded");
}
else {
    Console.WriteLine("Request Failed.");
}

Console.ReadLine();

Console.WriteLine("Finished");

As you can see the code here is also extremely simple it creates a new HttpClient, and creates a RestClient from it, and calling the connection method causes the above exception to be printed.

Setting the base URL for the HttpClient solves the exception problem but cause a BadRequest response from the API.

Setting both the base url for the HttpClient and explicitly setting the base URL for the Rest client works.