blazor Web 程序集服务对象引用未设置为对象的实例

Posted

技术标签:

【中文标题】blazor Web 程序集服务对象引用未设置为对象的实例【英文标题】:blazor web assembly service object reference not set to an instance of an object 【发布时间】:2021-02-16 13:45:11 【问题描述】:

我在 blazor wasm 中构建了一些解决方案,我需要在初始加载任何页面之前从我的 api 获取一些用户信息。

所以我有类似的服务

public class UserService

    private readonly HttpClient http;
    private User u;

    public User User
    
        get  return u; 
        set  u = value; 
    

    public UserService(HttpClient http)
    
        this.http = http;
        try
        
            GetUser();
        
        catch (Exception ex)
        
            this.u = null;
            Console.WriteLine("UserService Ctor failed to get user from api except:" + ex.Message);
        
    

    private async void GetUser()
    
        string endpoint = "user/getuser";
        this.u = await this.http.GetFromJsonAsync<User>(endpoint);
    

在startup.cs中

 builder.Services.AddSingleton<UserService>(new UserService(new HttpClient  BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) ) );

在索引中

  @if (this.u != null && u.User.Login != null ) @U.User.Login


[Inject]
private UserService u  get; set; 

当我跑步时,我得到了

  Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
  Unhandled exception rendering component: Object reference not set to an instance of an object.
  System.NullReferenceException: Object reference not set to an instance of an object.
  ..... line 9 so this with null username

所以我假设这个渲染是在这个 userService 被实例化之前......我应该如何处理这个以等待任何渲染,直到 UserService ctor 中的初始加载完成?

【问题讨论】:

渲染过程中不调用用户服务,错误是否消失,例如G。来自按钮点击处理程序? 顺便说一句:Blazor 有一个可以使用的默认 HTTP 实例,see here 是的,当我在 btn 上执行此操作时,单击就可以了 尝试检查 User 是否为空或使用空条件运算符。您的异步方法在初始化后稍后设置User 属性,或者它可能会失败并且永远不会设置它,并且您永远不会知道它,因为方法是async void 您可以将您的代码放入OnInitializedAsync()方法中,并将async void GetUser()的签名更改为async Task GetUser()async Task&lt;User&gt; GetUser() 【参考方案1】:

好的,谢谢大家 我是这样做的

        UserService u = new UserService(new HttpClient  BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) );
        await u.GetUser();
        builder.Services.AddSingleton<UserService>(u);

这种方式很好,ctor很简单

  public UserService(HttpClient http)
    
        this.http = http;
    

    public async Task GetUser()
    
        string endpoint = "user/getuser";
        this.u = await this.http.GetFromJsonAsync<User>(endpoint);
    

有没有更好的方法? 我知道我可以使用AuthenticationStateProvider,但我不想这样

【讨论】:

以上是关于blazor Web 程序集服务对象引用未设置为对象的实例的主要内容,如果未能解决你的问题,请参考以下文章

Blazor WASM 部署到 IIS 对象引用未设置为对象的实例

没有 Web 程序集的 blazor

stsadm -addsolution“对象引用未设置为对象的实例”

C#连接数据库出现未将对象引用实例

内容 JS 文件的 Blazor 服务器端 MIME 类型错误

“我正在 VS 上使用 ASP.NET 设计一个 Web 应用程序,用户应该上传图像,但我得到“对象引用未设置为对象的实例 [重复]