Search code examples
c#.net-corerazor-pagesblazor-client-side

Issue with Blazor


I'm creating a Blazor web app, inside of this App I have an API, c# classes, interfaces, controller, etc. When I run the App the razor page throws me an error related to a null value.

        NullReferenceException: Object reference not set to an instance of an object.
    Infra.Web.Pages.Subscriptions.BuildRenderTree(RenderTreeBuilder __builder) in Subscriptions.razor, line 15
Infra.Web.Pages.Subscriptions.BuildRenderTree(RenderTreeBuilder __builder) in Subscriptions.razor
-
                <th scope="col">Subscription Id</th>
                <th scope="col">Subscription Name</th>
                <th scope="col">Options</th>
            </tr>
        </thead>
        <tbody>
            @foreach(var sub in Subscriptions) { 
            <tr>
                <th scope="row">@sub.SubId</th>
                <td>@sub.SubscriptionId</td>
                <td>@sub.SubscriptionName</td>
                <td>
                    <a href="#" class="btn btn-primary m-1">Deploy</a>

This error is related to the for each "Subscriptions":

<tbody>
        @foreach(var sub in Subscriptions) { 
        <tr>
            <th scope="row">@sub.SubId</th>
            <td>@sub.SubscriptionId</td>
            <td>@sub.SubscriptionName</td>
            <td>
                <a href="#" class="btn btn-primary m-1">Deploy</a>
                <a href="#" class="btn btn-danger m-1">Delete</a>                    
            </td>
        </tr>
        }
    </tbody>

My Razor class has this code:

using Microsoft.AspNetCore.Components;
using Infra.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Infra.Web.Services;
    namespace Infra.Web.Pages
        {
            public class SubscriptionsBase : ComponentBase
            {
                [Inject]
                public ISubscriptionService SubscriptionService { get; set; }
                public IEnumerable<Subscription> Subscriptions { get; set; }
        
                protected  override async Task OnInitializedAsync()
                {
                    Subscriptions = (await SubscriptionService.GetSubscriptions()).ToList();
                }       
            }
        }

I have an interface defined.

using Infra.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
    namespace Infra.Web.Services
    {
        public interface ISubscriptionService
        {
            Task<IEnumerable<Subscription>> GetSubscriptions();
            Task<Subscription> GetSubscription(int id);
        }
    }

And another class

using Infra.Models;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
    namespace Infra.Web.Services
    {
        public class SubscriptionService : ISubscriptionService
        {
            private readonly HttpClient httpClient;
    
            public SubscriptionService(HttpClient httpClient)
            {
                this.httpClient = httpClient;
            }
    
            public async Task<Subscription> GetSubscription(int id)
            {
                return await httpClient.GetJsonAsync<Subscription>($"api/subscriptions/{id}");
            }
    
            public async Task<IEnumerable<Subscription>> GetSubscriptions()
            {
               return await httpClient.GetJsonAsync<Subscription[]>("api/subscriptions");
    
            }
        }
    }

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Infra.Web.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;


namespace Infra.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHttpClient<ISubscriptionService, SubscriptionService>(client =>
            {
                client.BaseAddress = new Uri("https://localhost:44322/");
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

The API seems to be working since I can execute all the methods, GET, PUT, POST, DELETE, but when I run the App I receive the error mentioned above.enter image description here

Browser API response. enter image description here

I have reviewed the code but I'm missing something, I don't have any errors or warnings being reported. All help is appreciated.


Solution

  • I was able to fix the issue, it was a little fix but important detail. Basically the razor page is expecting to have the values at runtime, and they aren't there when I initiate the App due to the async methods.

    The solution was to add a condition to the razor page:

    @if (Subscriptions == null)
    {
        <div class="spinner"></div>
    }
    

    Is basically showing a loading spinner until the values are added to the "Subscriptions parameter".

    The full code will be:

    @page "/"
    @inherits SubscriptionsBase
    <h3>Subscriptions</h3>
    @if (Subscriptions == null)
    {
        <div class="spinner"></div>
    }
    else
    { 
    
        <div class="table">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Subscription Id</th>
                        <th scope="col">Subscription Name</th>
                        <th scope="col">Options</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var sub in Subscriptions)
                    {
                        <tr>
                            <th scope="row">@sub.SubId</th>
                            <td>@sub.SubscriptionId</td>
                            <td>@sub.SubscriptionName</td>
                            <td>
                                <a href="#" class="btn btn-primary m-1">Deploy</a>
                                <a href="#" class="btn btn-danger m-1">Delete</a>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }
    

    Thank you all for your help.