I created a simple asp.net Web API that sends users from a SQL table.The API requires a key in the request header. I'm now creating a simple Blazor WebAssembly App that shows the users. I am just adding a simple httpclient:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7280/")});
and then I create the typical crud operations. For example the request for all the users:
public class UserService : IUserService
{
private readonly HttpClient httpClient;
public UserService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<List<UserDto>> GetUsers()
{
try
{
var response = await this.httpClient.GetAsync("api/Users");
if (response.IsSuccessStatusCode)
{
if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
{
return Enumerable.Empty<UserDto>().ToList();
}
return await response.Content.ReadFromJsonAsync<List<UserDto>>();
}
else
{
var alert = await response.Content.ReadAsStringAsync();
throw new Exception($"Http status:{response.StatusCode} - {alert}");
}
}
catch (Exception)
{
throw;
}
}
}
Is there a way to add header to all requests? Or do I have to make a custom request every time?