M Kenyon II
M Kenyon II

Reputation: 4254

Why is passing RequestUri as a param different than setting it in HttpRequestMessage

I have an HttpClient (generated by an IHttpClientFactory) with a BaseAddress of 'www.mydomain.com/3.0/'. I will have different methods hitting that client using different paths. So I start by setting up an HttpRequestMessage. I notice that these two implementations behave differently.

This:

var message = new HttpRequestMessage(HttpMethod.Get, $"account-lookup/?query={email}")
{
    Headers =
        {
            { key, value }
        }
};

works. But this:

var message = new HttpRequestMessage()
{
    Method = HttpMethod.Get,
    Headers =
        {
            { key, value }
        },
    RequestUri = new Uri($"account-lookup/?query={email}")
};

returns the exception Invalid URI: The format of the URI could not be determined.

We can't create a new Uri with a string like that, can we. Why don't we have a property or method that let's us pass in a path string? I'm assuming internally the constructor of HttpRequestMessage appends or concatenates the passed property to the BaseAddress?

I could/should probably do something like
RequestUri = new Uri(Client.BaseAddress + $"account-lookup/?query={email}")
but it would be nice to just tack the path string on somehow.

Upvotes: 1

Views: 732

Answers (1)

silkfire
silkfire

Reputation: 25935

You have to specify that the URL is relative for it to be combined with the base adress:

var message = new HttpRequestMessage()
{
    Method = HttpMethod.Get,
    Headers = ...,
    RequestUri = new Uri($"account-lookup/?query={email}", UriKind.Relative)
};

Upvotes: 6

Related Questions