来自 Blazor 组件的 Http 请求

Http request from blazor component

我正在尝试在我的 blazor 组件中向我的 API 发出一个 http 请求,我 运行 遇到了一些问题,而且我是 C# 的新手。我正在使用 Core 3.1。

Startup.cs:

services.AddHttpClient<MyHttpClient>(c => c.BaseAddress = Configuration["ServerUri"]);

服务文件夹/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
    }
}

我收到此错误:非静态字段、方法或 属性 需要对象引用 'member'

这是否有意义,或者是否有更好的方法来处理我的 http 请求?我做错了什么?

您注册了新客户端,但您仍然需要注入它:

@using Services
@inject MyHttpClient MyHttpClient

@code {
  ...
}

... or is there a better way to handle my http request?

您的 class 仅添加了一些错误处理,我不明白您是如何将其从 string 变为 IEnumerable<MyType>

考虑在直接使用原始 HttpClient 的地方使用 MyTypeService class。