gpt4 book ai didi

c# - Blazor WebAssembly 阻止 WebApi AllowAnonymous

转载 作者:行者123 更新时间:2023-12-04 09:58:39 28 4
gpt4 key购买 nike

我已经创建了一个 Blazor WebAssembly 项目,并希望提供一个具有一个公共(public)可用函数的 WebAPI。

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class SystemEvalApiController : ControllerBase
{
public SystemEvalApiController(AppDbContext context, IMapper mapper)
{...}

[Route("LatestEvals")]
[AllowAnonymous]
public ActionResult LatestEvals()

那是我的 Api Controller ,我应该可以调用它:

SystemEvalPublicViewModel = await Http
.GetFromJsonAsync<SystemEvalPublicViewModel>(
HttpService.BuildUrl("api/SystemEvalApi/LatestEvals"));

当我没有登录任何帐户时。但是我得到了这个错误:

info: System.Net.Http.HttpClient.JPB.BorannRemapping.ServerAPI.LogicalHandler[100]
Start processing HTTP request GET https://localhost:44330/api/SystemEvalApi/LatestEvals
blazor.webassembly.js:1 info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed.

看起来“DefaultAuthorizationService”无法识别 Anonymous 属性,但我找不到直接失败的地方。

如何声明无需登录即可从 HttpClient 访问的 WebAPI 函数。Microsoft.AspNetCore.Components.WebAssembly.Server 3.2.0.-rc1.20223.4

编辑:这是 ClientServices 的声明:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");

builder.Services.AddHttpClient("JPB.BorannRemapping.ServerAPI", client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
})
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("JPB.BorannRemapping.ServerAPI"));
builder.Services.AddTransient(e => new HttpService(e.GetService<HttpClient>()));
builder.Services.AddApiAuthorization();
builder.Services.AddBlazoredLocalStorage();

await builder.Build().RunAsync();

最佳答案

因此,每次您获取 HttpClient 时,它都会使用 BaseAddressAuthorizationMessageHandler 来尝试对请求进行身份验证。但在这种情况下,你的请求不应该被验证,所以你可以做类似的事情:

注册

builder.Services.AddHttpClient("JPB.BorannRemapping.ServerAPI.Anonymous", client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
});

用法

@inject IHttpClientFactory _factory

@code {
...
var httpClient = _factory.CreateClient("JPB.BorannRemapping.ServerAPI.Anonymous");
var httpService = new HttpService(httpClient);
SystemEvalPublicViewModel = await httpClient
.GetFromJsonAsync<SystemEvalPublicViewModel>(
httpService.BuildUrl("api/SystemEvalApi/LatestEvals"));
}

关于c# - Blazor WebAssembly 阻止 WebApi AllowAnonymous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61872050/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com