Home > Back-end >  Pass Base Address with Blazor WASM
Pass Base Address with Blazor WASM

Time:12-29

I am working on a Blazor WASM app with a backend API. This is done in .Net6

My issue is that I would like to be able to set my base address in one location - but what I have does not seem to work. I have verified that I can talk to the API if I put in a full URI.

My Client Program.CS file:

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();

My OrgHealthAuthorizationMessageHandler.cs

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

and this is the call I am trying to make work:

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

When I run that it does not work and give me an error indicating that its hitting the incorrect address - and I have verified that its placing the wrong local host info as part of the URI. My understanding was that the info out of the OrgHealthAuthorizationMessageHandler should be used. But it's not.

If I do this;

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

It works just fine. What am I missing in this configuration ?

CodePudding user response:

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

Your understanding is incorrect. When you use relative uris, the BaseAddress is appended. So you need to set it to https://localhost:7061/.

CodePudding user response:

you can assign base address like this

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);
  • Related