代码之家  ›  专栏  ›  技术社区  ›  Venson

Blazor WebAssembly阻止WebApi allowonymous

  •  0
  • Venson  · 技术社区  · 6 年前

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

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

    这是我的Api控制器,我应该能够调用它:

    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”无法识别匿名属性,但我找不到它直接失败的地方。

    如何声明一个WebAPI函数可以在不登录的情况下从HttpClient访问。 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();
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   agua from mars    6 年前

    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"));
    }