I have a project in BlazorServer and I'm creating document metadata (via a REST API) and uploading them (through another REST API).
My action after button click is very simple:
DocumentDto toCreate = new() { ... };byte[]? fileData = GetFileData();await _documentService.Create(toCreate, fileData);My _documentService.Create looks like this:
public async Task Create(DocumentDto input, byte[]? fileData){ try { var document = await _client.Create(input); if (document is not null && fileData is not null) await _attachmentClient.Create(document.Id, fileData); } catch (Exception ex) { _logger.LogError(ex, "Error during creating document. {serialized}", JsonSerializer.Serialize(input)); }}And finally, here is my _client.Create method:
public async Task<DocumentDto?> Create(DocumentDto input){ var result = await _httpClient.PostAsJsonAsync(Endpoint, input); return await result.Content.ReadFromJsonAsync<DocumentDto>();}And my _attachmentClient.Create method:
public Task Create(Guid documentId, byte[] fileData){ var content = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(fileData); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = "Document.pdf" }; content.Add(fileContent, "file", "Document.pdf"); return _httpClient.PostAsync($"{Endpoint}/{documentId}/pdf", content);}Both my clients are registered the same way:
services.AddHttpClient<DocumentClient>() .AddHttpMessageHandler<AuthenticationStateHandler>();services.AddHttpClient<DocumentAttachmentClient>() .AddHttpMessageHandler<AuthenticationStateHandler>();My AuthenticationStateHandler looks simple and works just fine for almost all situations:
public class AuthenticationStateHandler : DelegatingHandler{ private readonly IHttpContextAccessor _accessor; public AuthenticationStateHandler(IHttpContextAccessor accessor) { _accessor = accessor; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var service = _accessor.HttpContext?.RequestServices.GetService<TokenProvider>(); // service exists (is not null) for _client but not exists (is null) for _attachmentClient if (service is not null) { var token = await service.GetAccessTokenAsync(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); } return await base.SendAsync(request, cancellationToken); }}I have made a comment at line in AuthenticationStateHandler what is causing an error for me.
Does anyone have an idea why DelegatingHandler sometimes has access to the correct scope and sometimes not?