2

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?

Vencovsky
  • 23,092
  • 9
  • 82
  • 131
Steve
  • 2,480
  • 4
  • 35
  • 75

2 Answers2

3

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.

Vencovsky
  • 23,092
  • 9
  • 82
  • 131
1

1- create a class

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

2- put it as singleton

Services.AddSingleton<GlobalVariable>();

in the client side put it in the programm.cs file in the server side put it in the startup.cs file

now you can use it anywhere just write

GlobalVariable.Test

My refernce: https://github.com/dodyg

Mohamed Omera
  • 212
  • 2
  • 4
  • You shouldn't use a static parameter when combined with the Dependency injection. You should use a non static variable, then inject the instance of GlobalVariable (using the inject mechanism) to get the instance you declared in the AddSingleton line – Bob Vale Dec 16 '21 at 12:14