-1

InvalidOperationException: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.(HttpClient httpClient, string requestUri)

public class IndexBase:ComponentBase
{
    
    public readonly HttpClient httpClient = new HttpClient();

    public IEnumerable<Category> categories { get; set; }
   

    protected override async Task OnInitializedAsync()
    {
        
        categories=  await httpClient.GetJsonAsync<Category[]>("api/Category");

    }
}

and add code in startup

services.AddHttpClient("ServerApi",clint =>
        {
            clint.BaseAddress = new Uri("https://localhost:44363/");
        });
Nabi.M
  • 27
  • 7
  • you're missing `= new HttpClient();` – jps Nov 21 '20 at 18:45
  • when i add = new HttpClient() i have this error InvalidOperationException: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.(HttpClient httpClient, string requestUri) – Nabi.M Nov 21 '20 at 19:28

1 Answers1

0

Seems like your NullReferenceException appears because httpClient is null.

You should make httpClient like this so that dependency injection can set it properly:

public class IndexBase : ComponentBase
{
    [Inject]
    public HttpClient httpClient { get; set; }
}

It needs a property, not a field and requires an Inject attribute.

misticos
  • 609
  • 4
  • 20
  • i edit code like public class IndexBase : ComponentBase { public HttpClient httpClient { get; set; } } but NullReferenceException: Object reference not set to an instance of an object. – Nabi.M Nov 21 '20 at 19:29
  • you had a different error in question before, now its some invalid operation url. it states that the URL is invalid, you could try specifying that it is Absolute for base address and that it is relative for the request itself. – misticos Nov 21 '20 at 20:07
  • Nearly right, but this is Blazor, so you need to decorate the property with an `[Inject]` attribute to get it injected from the DI container. – Mister Magoo Nov 22 '20 at 02:29