Steve
Steve

Reputation: 4523

Global variable for web api base URL for Blazor

Currently, I have this working Blazor (Server Project) which have just a button which issue a Web Api GET request and it works without any issue.

This is my ConfigureServices method

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<HttpClient>();         
    }

and in my Index.razor

@page "/"
@inject HttpClient http;
@using Models

<button @onclick="@GetMovies">Get Movies</button>

<table>
    <thead>
        <tr><th>Movie</th></tr>
    </thead>
    <tbody>
        @foreach(var movie in @Movies)
        {
        <tr><td>@movie.MovieTitle</td></tr>
        }
    </tbody>
</table>

@code{
    List<Movie> Movies;

    private async Task GetMovies()
    {
        Movies = await http.GetJsonAsync<List<Movie>>("http://localhost:54124/api/Movies");
    }
}

How do I put http://localhost:54124 into just one single location like global variable? Do it at ConfigureServices method?

Upvotes: 2

Views: 3360

Answers (2)

Mohamed Omera
Mohamed Omera

Reputation: 263

1- create a class

public class GlobalVariable
{
    public string Test { get; set; } = "any thing";
} 

2- put it as singleton

Services.AddSingleton<GlobalVariable>();

now you can use it anywhere just write

@inject GlobalVariable _globalVariable
_globalVariable.Test

Upvotes: 1

Vencovsky
Vencovsky

Reputation: 31683

You should store it in appsettings.json.

If you are using WASM, appsettings.json will be inside wwwroot.

And to get the value from it, you can check this question where the answer to it my change according to the version of .net core and there is more than one way of doing it.

Upvotes: 3

Related Questions