【发布时间】:2021-07-21 03:01:27
【问题描述】:
我有一个允许匿名的 API 端点。我已经在 Postman 中确认它适用于匿名和经过身份验证的用户并返回正确的 JSON。
由于可以匿名调用端点,所以在我的 Blazor WASM http Service 中,我构造了以下内容,一个不带令牌发送的请求,一个带令牌发送的请求。
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);
}
}
我在我的组件中声明了社区。p>
private CommunityDto Community { get; set; } = new CommunityDto();
在我的组件的 OnInitializedAsync 方法中,我有以下内容:
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>();
}
}
所有的html是:
<span>@CommunityId</span>
设置断点似乎没用,但我不知道是什么原因导致控制台出现此错误。有什么想法吗?
【问题讨论】: