You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中从类实现依赖注入时遇对象无法访问问题求助

问题分析与解决方案

核心问题出在你的HuntressAPI类设计上——它的核心方法都是静态方法,且没有存储获取到的组织数据的实例属性,导致注入的实例对象既无法调用静态方法,也拿不到API返回的数据。以下是具体修复步骤:


1. 重构HuntressAPI类

将静态方法改为实例方法,添加存储组织数据的属性,移除控制台输出逻辑,改为将数据保存到实例属性中:

public class HuntressAPI
{
    // 实例属性:存储获取到的组织数据
    public List<Organization> Organizations { get; private set; } = new List<Organization>();

    private readonly HttpClient _httpClient;

    // 构造函数注入HttpClient(Blazor推荐的标准方式)
    public HuntressAPI(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task FetchOrganizationsAsync()
    {
        string apiUrl = "your-api-url";
        string username = "your-username";
        string password = "your-password";

        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
        _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);

        try
        {
            HttpResponseMessage response = await _httpClient.GetAsync(apiUrl);

            if (response.IsSuccessStatusCode)
            {
                string jsonResponse = await response.Content.ReadAsStringAsync();
                var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);

                Organizations = apiResponse.Organizations ?? new List<Organization>();
            }
            else
            {
                throw new HttpRequestException($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        catch (Exception ex)
        {
            Organizations.Clear();
            throw;
        }
    }

    public class Organization
    {
        public string Name { get; set; }
        public int agents_count { get; set; }
    }

    // 补充ApiResponse类(确保和API返回结构匹配)
    public class ApiResponse
    {
        public List<Organization> Organizations { get; set; }
    }
}

2. 修正Program.cs中的服务注册

由于现在使用构造函数注入HttpClient,需要改用AddHttpClient注册服务:

// 替换原来的AddTransient,改用框架推荐的AddHttpClient
builder.Services.AddHttpClient<HuntressAPI>();

3. 修改Licenses.razor页面加载并展示数据

在页面初始化时调用API获取数据,然后绑定渲染表格:

@page "/licenses"
@inject HuntressAPI huntress
@inject ILogger<Licenses> Logger

<h3>Licenses</h3>

<p>Shows the current licensing count of the services</p>

@if (huntress.Organizations.Count == 0)
{
    <p>加载中...</p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Site Name</th>
                <th>Huntress Agent Count</th>
                <th>Total Count</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var org in huntress.Organizations)
            {
                <tr>
                    <td>@org.Name</td>
                    <td>@org.agents_count</td>
                    <td>@org.agents_count</td> <!-- 替换为你实际的Total Count逻辑 -->
                </tr>
            }
        </tbody>
    </table>
}

@code {
    protected override async Task OnInitializedAsync()
    {
        try
        {
            // 页面初始化时调用API拉取数据
            await huntress.FetchOrganizationsAsync();
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "获取Huntress数据失败");
        }
    }
}

关键要点

  • 静态方法属于类本身,依赖注入的是类的实例,因此必须改为实例方法才能通过注入对象调用。
  • Blazor页面需要绑定实例属性来渲染数据,所以必须将API返回的数据保存到实例属性中。
  • 避免手动创建HttpClient,通过构造函数注入可以利用Blazor的HttpClient生命周期管理和配置。

内容的提问来源于stack exchange,提问作者pandapunk94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 11:53:09