I'm trying to make an http request in my blazor component to my API and I'm running into some issues, also I'm new to C#. I'm using Core 3.1.
Startup.cs:
services.AddHttpClient<MyHttpClient>(c => c.BaseAddress = Configuration["ServerUri"]);
Services folder / MyHttpClient.cs:
using System.Net.Http;
using System.Threading.Tasks;
namespace My.Namespace
{
public class MyHttpClient
{
private readonly HttpClient _client;
private string responseString = null;
public MyHttpClient(HttpClient client)
{
_client = client;
}
public async Task<string> HttpGets(string requestUri)
{
{
try
{
HttpResponseMessage response = new HttpResponseMessage();
response = await _client.GetAsync(requestUri);
responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
return responseString;
}
}
}
Component.razor:
@using Services
@code {
public IEnumerable<MyType> Data;
protected override async Task OnInitializedAsync()
{
Data = await MyHttpClient.HttpGets("/api/getdata"); // I want to do something like this
}
}
I'm getting this error: An object reference is required for the nonstatic field, method, or property 'member'
Also does this make sense or is there a better way to handle my http request? What am I doing wrong?
CodePudding user response:
You register the new Client but you still have to inject it:
@using Services
@inject MyHttpClient MyHttpClient
@code {
...
}
... or is there a better way to handle my http request?
Your class only adds some errorhandling and I don't see how you make it go from string
to IEnumerable<MyType>
.
Consider using a MyTypeService class where you use the original HttpClient directly.