jpp1jpp1
jpp1jpp1

Reputation: 181

Anonymous api call, baseAddress is null at Frontend

I'm following this link to get some of my pages to access the API anonymously.

Tech:

My code:

(Program.cs)

 builder.Services.AddHttpClient("NoAuthenticationClient", httpClient =>
 httpClient.BaseAddress = new Uri("https://localhost:7295/"));

Btw, I cannot use new Uri(builder.HostEnvironment.BaseAddress) as suggested in some places, I get:

CS1061 'type' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?).'

Did they move it elsewhere in NET7?

(Index.razor)

var NoAuthenticationClientWrng = ClientFactory.CreateClient("FakeClient"); //NOT defined at server program.cs
var NoAuthenticationClient = ClientFactory.CreateClient("NoAuthenticationClient"); //defined at server program.cs

var result = await NoAuthenticationClient.GetFromJsonAsync<List<Things>>("api/MyController/GetList");

NoAuthenticationClientWrng & NoAuthenticationClient look the same to me, I guess ClientFactory.CreateClient cannot retrieve the registered "NoAuthenticationClient". The baseAddress property is null in both cases.

The code returns:

"An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set"

when we consume.

If i add these two lines before consuming:

var NoAuthenticationClientWrng = ClientFactory.CreateClient("FakeClient"); //NOT defined at server program.cs
var NoAuthenticationClient = ClientFactory.CreateClient("NoAuthenticationClient"); //defined at server program.cs

var str = HostEnvironment.BaseAddress; //needs @using Microsoft.AspNetCore.Components.WebAssembly.Hosting
        NoAuthenticationClient.BaseAddress = new Uri(str);

var result = await NoAuthenticationClient.GetFromJsonAsync<List<Things>>("api/MyController/GetList");

It works wo a logged user.

Upvotes: 0

Views: 197

Answers (1)

jpp1jpp1
jpp1jpp1

Reputation: 181

I feel so dumb. 10 minutes after asking this question I found what was wrong. You have to add the (Program.cs) code block in the client project NOT the server project.

It doesn't help both projects have a Program.cs

Upvotes: 0

Related Questions