C
C#10mo ago
P R Deltoid

Setting BaseURI for named HttpClient in DI not including trailing string

I am trying to use a named HttpClient setup in a Blazor WASM application. In my DI setup, I create it using the following:
builder.Services.AddScoped<AuthorizationMessageHandler>();
builder.Services.AddHttpClient("apiClient",
client => client.BaseAddress = new Uri("http://localhost:5199/api/v1/"))
.AddHttpMessageHandler(sp =>
sp.GetRequiredService<AuthorizationMessageHandler>().ConfigureHandler(new[] { "http://localhost:5199" }));

builder.Services.AddScoped<HttpClient>(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("apiClient"));
builder.Services.AddScoped<AuthorizationMessageHandler>();
builder.Services.AddHttpClient("apiClient",
client => client.BaseAddress = new Uri("http://localhost:5199/api/v1/"))
.AddHttpMessageHandler(sp =>
sp.GetRequiredService<AuthorizationMessageHandler>().ConfigureHandler(new[] { "http://localhost:5199" }));

builder.Services.AddScoped<HttpClient>(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("apiClient"));
However, when the HttpClient is injected into a Razor page and used to query my API using this code:
ChorePageResultDTO res = await httpClient.GetFromJsonAsync<ChorePageResultDTO>($"/Chores?page={state.Page+1}?pageSize={state.PageSize}") ?? new ChorePageResultDTO();
ChorePageResultDTO res = await httpClient.GetFromJsonAsync<ChorePageResultDTO>($"/Chores?page={state.Page+1}?pageSize={state.PageSize}") ?? new ChorePageResultDTO();
it makes a request like so:
info: System.Net.Http.HttpClient.apiClient.LogicalHandler[100]
Start processing HTTP request GET http://localhost:5199/Chores?page=1?pageSize=10
info: System.Net.Http.HttpClient.apiClient.ClientHandler[100]
Sending HTTP request GET http://localhost:5199/Chores?page=1?pageSize=10
info: System.Net.Http.HttpClient.apiClient.LogicalHandler[100]
Start processing HTTP request GET http://localhost:5199/Chores?page=1?pageSize=10
info: System.Net.Http.HttpClient.apiClient.ClientHandler[100]
Sending HTTP request GET http://localhost:5199/Chores?page=1?pageSize=10
It seems to be dropping the "/api/v1/" portion of the base URI for the request but using the base host/port that I provided (the port running this web application is 5000, which I assume would be the HttpClient default if I hadn't provided a new BaseAddress in my configuration.) Why is it dropping this portion and how can I get it to stop?
1 Reply
P R Deltoid
P R Deltoid10mo ago
Apparently, when using the HttpClient, my requestUri had a leading slash ("/Chores") and HttpClient was getting messed up trying to combine it with my BaseAddress for some reason. Removing the slash from my HttpClient's Get request fixes this issue. I was fixated on the configuration and didn't think that I may just be misusing the client. A bit confusing but all is well.