I have an API endpoint which allows anonymous. I have confirmed in Postman it is working for anonymous and authenticated users and returning proper JSON.
Because the endpoint can be called anonymously, in my Blazor WASM http Service, I have constructed the following, one request to send without a token, one request to send with a token.
private readonly HttpClient httpClient;
private readonly IHttpClientFactory httpClientFactory;
private readonly HttpClient anonHttp;
public CommunityHttpService(HttpClient httpClient, IHttpClientFactory httpClientFactory)
{
if (httpClient == null) throw new ArgumentNullException("Http is null.");
this.httpClient = httpClient;
this.httpClientFactory = httpClientFactory;
anonHttp = httpClientFactory.CreateClient("AnonAPI");
}
public async Task<HttpResponseMessage> GetCommunity(Guid communityId, bool userIsAuthenticated)
{
if (!userIsAuthenticated)
{
// make anonymous api call without bearer token to avoid error
return await anonHttp.GetAsync($"api/communities/GetCommunity/" + communityId);
}
else
{
return await httpClient.GetAsync($"api/communities/GetCommunity/" + communityId);
}
}
I declare the Community in my component.
private CommunityDto Community { get; set; } = new CommunityDto();
in my OnInitializedAsync method of the component, I have the following:
if (!string.IsNullOrEmpty(CommunityId.ToString()))
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
HttpResponseMessage apiResponse;
if (user.Identity.IsAuthenticated)
{
apiResponse = await CommunityService.GetCommunity(CommunityId, true);
}
else
{
apiResponse = await CommunityService.GetCommunity(CommunityId, false);
}
if (apiResponse.IsSuccessStatusCode)
{
Community = await apiResponse.Content.ReadFromJsonAsync<CommunityDto>();
}
}
All the html is:
<span>@CommunityId</span>
Setting breakpoints seems to be useless, but I don't know what could be causing this error in the console. Any ideas?