使用 Blazor WASM 传递基地址

Pass Base Address with Blazor WASM

我正在开发带有后端 API 的 Blazor WASM 应用程序。这是在 .Net6

中完成的

我的问题是我希望能够在一个位置设置我的基地址 - 但我所拥有的似乎不起作用。我已经验证如果输入完整的 URI,我可以与 API 通信。

我的客户Program.CS 文件:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped<OrgHealthAuthorizationMessageHandler>();
builder.Services.AddHttpClient("OrgHealth.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
   .AddHttpMessageHandler<OrgHealthAuthorizationMessageHandler>();
builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("OrgHealth.ServerAPI"));


builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://authorghealth.onmicrosoft.com/22222222-2222-22222-22222-222222222222/API.Access.All");
});

await builder.Build().RunAsync();

我的OrgHealthAuthorizationMessageHandler.cs

public class OrgHealthAuthorizationMessageHandler : AuthorizationMessageHandler
{
    public OrgHealthAuthorizationMessageHandler(IAccessTokenProvider AProvider, NavigationManager ANavigation) : base(AProvider, ANavigation)
    {
        ConfigureHandler(authorizedUrls: new[] {  "https://localhost:7061/" });
    }
}

这是我正在尝试进行的调用:

var test = await Http.GetStringAsync("AzureStorage/GetTestData");

当我 运行 它不工作时给我一个错误,指出它击中了不正确的地址 - 我已经验证它放置了错误的本地主机信息作为 URI 的一部分。我的理解是应该使用来自 OrgHealthAuthorizationMessageHandler 的信息。但事实并非如此。

如果我这样做;

var test = await Http.GetStringAsync("https://localhost:7061/AzureStorage/GetTestData");

它工作得很好。我在此配置中缺少什么?

你可以这样分配基地址

var baseAddress = "https://localhost:7061";
var api = "/AzureStorage/GetTestData";

Http.BaseAddress = new Uri(baseAddress);

.... other int http client code

var test = await Http.GetStringAsync(api);

My understanding was that the info out of the OrgHealthAuthorizationMessageHandler should be used. But it's not.

您的理解有误。当您使用相对 uris 时,会附加 BaseAddress。所以需要设置为https://localhost:7061/.