System.NullReferenceException: ‘Object reference not set to an instance of an object.’ problem with blazor server app

I’m making my first blazor application and I’mrunning into an error, when I’m trying to get a specific User by Id.

for some contexts I’m using a Blazor server as frontend with a .NET 8 API as a backend

Blazor page code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@page "/User"
@page "/User/{Id:int}"
@rendermode InteractiveServer
@using System.Net.Http
@using Models
@using System.Text.Json;
@using System.Text
@using System.Security.Cryptography;
@inject HttpClient HttpClient
@inject NavigationManager NavManager
@if (Id == null)
{
<h3>User Add</h3>
}
else
{
<h3>User Edit</h3>
}
<form method="post" @onsubmit="AddUser" @formname="UserAdd" class="mt-4">
<AntiforgeryToken />
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<InputText type="text" @bind-Value="user!.Name" class="form-control" required />
</div>
<div class="mb-3">
<label for="Company" class="form-label">Company:</label>
<InputText type="text" @bind-Value="user!.Company" class="form-control" required />
</div>
<div class="mb-3">
<label for="Department" class="form-label">Department:</label>
<InputText type="text" @bind-Value="user!.Department" class="form-control" required />
</div>
<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<InputText type="email" @bind-Value="user!.Email" class="form-control" required />
</div>
<div class="mb-3">
<label for="Password" class="form-label">Password:</label>
<InputText type="password" @bind-Value="user!.Password" class="form-control" required />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@code {
[Parameter]
public int? Id { get; set; }
[SupplyParameterFromForm]
public User? user { get; set; }
protected override async Task OnInitializedAsync()
{
if (Id != null)
{
try{
var response = await HttpClient.GetAsync($"https://localhost:7183/api/User/{Id}");
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
user = JsonSerializer.Deserialize<User>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
catch (Exception ex)
{
// Handle error
Console.WriteLine("Error getting user: " + ex.Message);
}
}
else
{
user ??= new();
}
}
void AddUser()
{
try
{
byte[] salt = GenerateSalt();
user.Password = HashPassword(user.Password, salt);
var client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7183/api/User");
var json = JsonSerializer.Serialize(user);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.PostAsync("User", content).Result;
NavManager.NavigateTo("/UserOverview");
}
catch (Exception ex)
{
// Handle error
Console.WriteLine("Error adding user: " + ex.Message);
}
}
private string HashPassword(string password, byte[] salt)
{
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000))
{
byte[] hash = pbkdf2.GetBytes(32); // 32 bytes for SHA256
byte[] hashBytes = new byte[36]; // 32 bytes for hash + 4 bytes for salt
Array.Copy(salt, 0, hashBytes, 0, 4);
Array.Copy(hash, 0, hashBytes, 4, 32);
return Convert.ToBase64String(hashBytes);
}
}
private byte[] GenerateSalt()
{
byte[] salt = new byte[4]; // 4 bytes for salt
using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
{
rngCsp.GetBytes(salt);
}
return salt;
}
}
</code>
<code>@page "/User" @page "/User/{Id:int}" @rendermode InteractiveServer @using System.Net.Http @using Models @using System.Text.Json; @using System.Text @using System.Security.Cryptography; @inject HttpClient HttpClient @inject NavigationManager NavManager @if (Id == null) { <h3>User Add</h3> } else { <h3>User Edit</h3> } <form method="post" @onsubmit="AddUser" @formname="UserAdd" class="mt-4"> <AntiforgeryToken /> <div class="mb-3"> <label for="name" class="form-label">Name:</label> <InputText type="text" @bind-Value="user!.Name" class="form-control" required /> </div> <div class="mb-3"> <label for="Company" class="form-label">Company:</label> <InputText type="text" @bind-Value="user!.Company" class="form-control" required /> </div> <div class="mb-3"> <label for="Department" class="form-label">Department:</label> <InputText type="text" @bind-Value="user!.Department" class="form-control" required /> </div> <div class="mb-3"> <label for="email" class="form-label">Email:</label> <InputText type="email" @bind-Value="user!.Email" class="form-control" required /> </div> <div class="mb-3"> <label for="Password" class="form-label">Password:</label> <InputText type="password" @bind-Value="user!.Password" class="form-control" required /> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> @code { [Parameter] public int? Id { get; set; } [SupplyParameterFromForm] public User? user { get; set; } protected override async Task OnInitializedAsync() { if (Id != null) { try{ var response = await HttpClient.GetAsync($"https://localhost:7183/api/User/{Id}"); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); user = JsonSerializer.Deserialize<User>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (Exception ex) { // Handle error Console.WriteLine("Error getting user: " + ex.Message); } } else { user ??= new(); } } void AddUser() { try { byte[] salt = GenerateSalt(); user.Password = HashPassword(user.Password, salt); var client = new HttpClient(); client.BaseAddress = new Uri("https://localhost:7183/api/User"); var json = JsonSerializer.Serialize(user); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = client.PostAsync("User", content).Result; NavManager.NavigateTo("/UserOverview"); } catch (Exception ex) { // Handle error Console.WriteLine("Error adding user: " + ex.Message); } } private string HashPassword(string password, byte[] salt) { using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000)) { byte[] hash = pbkdf2.GetBytes(32); // 32 bytes for SHA256 byte[] hashBytes = new byte[36]; // 32 bytes for hash + 4 bytes for salt Array.Copy(salt, 0, hashBytes, 0, 4); Array.Copy(hash, 0, hashBytes, 4, 32); return Convert.ToBase64String(hashBytes); } } private byte[] GenerateSalt() { byte[] salt = new byte[4]; // 4 bytes for salt using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider()) { rngCsp.GetBytes(salt); } return salt; } } </code>
@page "/User"
@page "/User/{Id:int}"
@rendermode InteractiveServer
@using System.Net.Http
@using Models
@using System.Text.Json;
@using System.Text
@using System.Security.Cryptography;
@inject HttpClient HttpClient
@inject NavigationManager NavManager


@if (Id == null)
{
    <h3>User Add</h3>
}
else
{
    <h3>User Edit</h3>
}

<form method="post" @onsubmit="AddUser" @formname="UserAdd" class="mt-4">
    <AntiforgeryToken />

    <div class="mb-3">
        <label for="name" class="form-label">Name:</label>
        <InputText type="text" @bind-Value="user!.Name" class="form-control" required />
    </div>

    <div class="mb-3">
        <label for="Company" class="form-label">Company:</label>
        <InputText type="text" @bind-Value="user!.Company" class="form-control" required />
    </div>

    <div class="mb-3">
        <label for="Department" class="form-label">Department:</label>
        <InputText type="text" @bind-Value="user!.Department" class="form-control" required />
    </div>

    <div class="mb-3">
        <label for="email" class="form-label">Email:</label>
        <InputText type="email" @bind-Value="user!.Email" class="form-control" required />
    </div>

    <div class="mb-3">
        <label for="Password" class="form-label">Password:</label>
        <InputText type="password" @bind-Value="user!.Password" class="form-control" required />
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>


@code {
    [Parameter]
    public int? Id { get; set; }

    [SupplyParameterFromForm]
    public User? user { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (Id != null)
        {
            try{
                var response = await HttpClient.GetAsync($"https://localhost:7183/api/User/{Id}");
                response.EnsureSuccessStatusCode();

                var json = await response.Content.ReadAsStringAsync();
                user = JsonSerializer.Deserialize<User>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            }
            catch (Exception ex)
            {
                // Handle error
                Console.WriteLine("Error getting user: " + ex.Message);
            }
        }
        else
        {
            user ??= new();
        }
    }

    void AddUser()
    {
        try
        {
            byte[] salt = GenerateSalt();
            user.Password = HashPassword(user.Password, salt);

            var client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:7183/api/User");

            var json = JsonSerializer.Serialize(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = client.PostAsync("User", content).Result;

            NavManager.NavigateTo("/UserOverview");
        }
        catch (Exception ex)
        {
            // Handle error
            Console.WriteLine("Error adding user: " + ex.Message);
        }
    }

    private string HashPassword(string password, byte[] salt)
    {
        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000))
        {
            byte[] hash = pbkdf2.GetBytes(32); // 32 bytes for SHA256
            byte[] hashBytes = new byte[36]; // 32 bytes for hash + 4 bytes for salt

            Array.Copy(salt, 0, hashBytes, 0, 4);
            Array.Copy(hash, 0, hashBytes, 4, 32);

            return Convert.ToBase64String(hashBytes);
        }
    }

    private byte[] GenerateSalt()
    {
        byte[] salt = new byte[4]; // 4 bytes for salt
        using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
        {
            rngCsp.GetBytes(salt);
        }
        return salt;
    }
}

And the API methode i have:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>group.MapGet("/{id}", async Task<Results<Ok<User>, NotFound>> (int id, DataContext db) =>
{
return await db.User.AsNoTracking()
.FirstOrDefaultAsync(model => model.Id == id)
is User model
? TypedResults.Ok(model)
: TypedResults.NotFound();
})
.WithName("GetUserById")
.WithOpenApi();
</code>
<code>group.MapGet("/{id}", async Task<Results<Ok<User>, NotFound>> (int id, DataContext db) => { return await db.User.AsNoTracking() .FirstOrDefaultAsync(model => model.Id == id) is User model ? TypedResults.Ok(model) : TypedResults.NotFound(); }) .WithName("GetUserById") .WithOpenApi(); </code>
group.MapGet("/{id}", async Task<Results<Ok<User>, NotFound>> (int id, DataContext db) =>
{
    return await db.User.AsNoTracking()
        .FirstOrDefaultAsync(model => model.Id == id)
        is User model
            ? TypedResults.Ok(model)
            : TypedResults.NotFound();
})
.WithName("GetUserById")
.WithOpenApi();

after the line:
var response = await HttpClient.GetAsync($"https://localhost:7183/api/User/{Id}");

i get this error message:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=CalibrationReportingToolFrontend
StackTrace:
at CalibrationReportingToolFrontend.Components.Pages.OtherPages.UserAdd.BuildRenderTree(RenderTreeBuilder __builder)
</code>
<code>System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=CalibrationReportingToolFrontend StackTrace: at CalibrationReportingToolFrontend.Components.Pages.OtherPages.UserAdd.BuildRenderTree(RenderTreeBuilder __builder) </code>
System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=CalibrationReportingToolFrontend
  StackTrace:
   at CalibrationReportingToolFrontend.Components.Pages.OtherPages.UserAdd.BuildRenderTree(RenderTreeBuilder __builder)

I thought maybe the Id i was looking for doesn’t exist in the DB so i tried this:
var response = await HttpClient.GetAsync("https://localhost:7183/api/User/6");

Beside that i also tested my API endpoint and this seems to be working as expected

New contributor

JuleanCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật