Matblazor: Blazor Server Side - Http Client doesn't exist by default

Created on 18 Aug 2019  Â·  2Comments  Â·  Source: SamProf/MatBlazor

Hi, thanks for the hard work. It is just a note.

Table component injects Http Client. However, on blazor server-side, it doesn't exist. you may want to add in the installation steps, adding something like:

services.AddScoped<HttpClient>();

OR

services.AddScoped<HttpClient>(s =>
    {
        var uriHelper = s.GetRequiredService<IUriHelper>();
        return new HttpClient
        {
            BaseAddress = new Uri(uriHelper.GetBaseUri())
        };
    });
table

Most helpful comment

Stumble upon the same problem. Rather then require an inject through services.AddScoped I would recommend changing the component itself to support situations where http is not available. To allow this the following code adaptation should work:

Change BaseMatComponent to use _OwningComponentBase_ instead of ComponentBase (or similar to cover MatTable only and not "every" component)
public abstract class BaseMatComponent : OwningComponentBase, IBaseMatComponent, IDisposable

Add to MatTable
@using Microsoft.Extensions.DependencyInjection

private System.Net.Http.HttpClient Http { get; set; }

protected override async Task OnInitializedAsync()
{
    Http = ScopedServices.GetService<System.Net.Http.HttpClient>();
…

Remove from MatTable
@inject System.Net.Http.HttpClient Http

Also the functions SearchData and SearchPagedData have to be adapated to reflect that http might be NULL.

All 2 comments

Yes, sure.
Also like I sad before MatTable will have big rewriting. So, in future this problem should be resolved.

Stumble upon the same problem. Rather then require an inject through services.AddScoped I would recommend changing the component itself to support situations where http is not available. To allow this the following code adaptation should work:

Change BaseMatComponent to use _OwningComponentBase_ instead of ComponentBase (or similar to cover MatTable only and not "every" component)
public abstract class BaseMatComponent : OwningComponentBase, IBaseMatComponent, IDisposable

Add to MatTable
@using Microsoft.Extensions.DependencyInjection

private System.Net.Http.HttpClient Http { get; set; }

protected override async Task OnInitializedAsync()
{
    Http = ScopedServices.GetService<System.Net.Http.HttpClient>();
…

Remove from MatTable
@inject System.Net.Http.HttpClient Http

Also the functions SearchData and SearchPagedData have to be adapated to reflect that http might be NULL.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

esso23 picture esso23  Â·  5Comments

snerting picture snerting  Â·  3Comments

kristof12345 picture kristof12345  Â·  5Comments

lkmcelik picture lkmcelik  Â·  4Comments

vcaraulean picture vcaraulean  Â·  6Comments