14

I am trying to call an api during the blazor(client side) startup to load language translations into the ILocalizer.

At the point I try and get the .Result from the get request blazor throws the error in the title.

This can replicated by calling this method in the program.cs

  private static void CalApi()
    {
        try
        {
            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(@"https://dummy.restapiexample.com/api/v1/employees");
            string path = "ididcontent.json";
            string response = httpClient.GetStringAsync(path)?.Result;
            Console.WriteLine(response);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error getting api response: " + ex);
        }

    }

3 Answers 3

14

Avoid .Result, it can easily deadlock. You get this error because the mechanism is not (cannot be) supported on single-threaded webassembly. I would consider it a feature. If it could wait on a Monitor it would freeze.

private static async Task CalApi()
{
   ... 
   string response = await httpClient.GetStringAsync(path); 
   ...
}

All events and lifecycle method overrides can be async Task in Blazor, so you should be able to fit this in.

Sign up to request clarification or add additional context in comments.

2 Comments

or in the DI setup
DI container requires sync resolution of the services. If any needs async operation, than it's impossible to do in blazor
4

In Program.cs

 public static async Task Main(string[] args)
 {

    ......

    builder.Services.AddSingleton<SomeService>();

    var host = builder.Build();       

    ...

call your code here but use await

    var httpClient = host.Services.GetRequiredService<HttpClient>();
    string response = await httpClient.GetStringAsync(path);
    ...

    var someService = host.Services.GetRequiredService<SomeService>();
    someService.SomeProperty = response;

    await host.RunAsync();

1 Comment

good suggestion. I think Ilocalizer isn't async but yeah I think you're right I might have to right my own
1

This is a example best:

var client= new ProductServiceGrpc.ProductServiceGrpcClient(Channel);
            category =  (await client.GetCategoryAsync(new GetProductRequest() {Id = id})).Category;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.