Reputation: 553
I have a simple Blazor WASM app (.net 8) that I am debugging locally on my laptop.
I have published an Azure Function to my Azure Portal, and ensure that CORS is opened to for example http://localhost:1010 where the local blazor WASM in VS Code is running on my laptop.
Good news I can call a function form my locally debugged Blazor WASM app in VS Code and call the online Azure Function, once ... and also pass in the header the x-functions-key code.
However upon 2nd call I receive ..:
n-mdm.azurewebsites.net/api/GetTable 401 (Unauthorized)
Upvotes: 0
Views: 222
Reputation: 553
To make this more elegant, my WASM web application uses this class:
public class HttpHosted: HttpClient
{
public HttpClient? HttpClient { get; set; }
public string? Key {get;set;}
public HttpHosted(string key)
{
this.Key = key;
if (this.DefaultRequestHeaders.Count() == 0)
{
this.DefaultRequestHeaders.Add("x-functions-key", this.Key );
}
}
}
public class HttpLocal: HttpClient
{
public HttpClient? HttpClient { get; set; }
}
Which is setup in Program.cs
builder.Services.AddScoped(sp => new HttpHosted(Configuration["HostedAzureFunctionKey"]) { BaseAddress = new Uri(Configuration["HostedAzureFunctionURL"])} );
I am using a configuration builder to obtain keys from appsettings.json, not yet sure if this will work when published (the WASM static web app), however it is calling an Azure function that is already published.
IConfiguration Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Upvotes: 0
Reputation: 553
I found a solution, by not including the DefaultRequestHeaders again if it has already been added, will look for a more elegant solution but this is working for now:
if (HttpHosted.DefaultRequestHeaders.Count() == 0)
{
HttpHosted.DefaultRequestHeaders.Add("x-functions-key", HttpHosted.Key );
}
var response = await HttpHosted.PostAsJsonAsync("api/GetTable", dictionary);
Upvotes: 1