Short answer you can !!
here is how to do it
1- created new Blazor server app
2- Edit configure service
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddControllersWithViews();
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/"));
}
the only diff here is
services.AddControllersWithViews();
services.AddHttpClient("LocalApi", client => client.BaseAddress = new Uri("https://localhost:44333/")); // you could change this based on your project the right way is to get it from appsettings.json
3- Edit Configure as following
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); //<======= this is the line you need to add
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
4- In your Blazor page you could use one of the following options
If you decided to use htppFactory you should add the following code in the top of your page
@inject IHttpClientFactory ClientFactory
And inside your function use it as follwoing
var clientlocal = ClientFactory.CreateClient("LocalApi");
var res = await clientlocal.GetStringAsync("api/values/5");
of course you need to change your function signature
async Task RetrieveGet()
the other option which is creating your own client
you need to call your api as following
HttpClient Http = new HttpClient();
string baseUrl = "https://localhost:44333/";
var temp2 = await Http.GetStringAsync($"{baseUrl}api/values/5");
of course you need to change your function signature
async Task RetrieveGet()
Here is screenshot for either way
and here is the return result
Here you have it
Let me know if you have any questions
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…