why I got an NullReferenceException in the validation phase?

ayman awadallah 30 Reputation points
2023-12-28T18:09:37.21+00:00

0

this is a blazor 8 server side interactiveserver render mode exception detail

System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object.
Source=Microsoft.AspNetCore.SignalR.Core StackTrace: at Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(IClientProxy clientProxy, String method, Object arg1, Object arg2, Object arg3, CancellationToken cancellationToken) in Microsoft.AspNetCore.SignalR\ClientProxyExtensions.cs:line 26 exception stack

Microsoft.AspNetCore.SignalR.Core.dll!Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(Microsoft.AspNetCore.SignalR.IClientProxy clientProxy, string method, object arg1, object arg2, object arg3, System.Threading.CancellationToken cancellationToken) Line 26 C# Microsoft.AspNetCore.Components.Server.dll!Microsoft.AspNetCore.Components.Server.Circuits.RemoteJSRuntime.EndInvokeDotNet(Microsoft.JSInterop.Infrastructure.DotNetInvocationInfo invocationInfo, Microsoft.JSInterop.Infrastructure.DotNetInvocationResult invocationResult) Line 98 C# Microsoft.JSInterop.dll!Microsoft.JSInterop.Infrastructure.DotNetDispatcher.EndInvokeDotNetAfterTask(System.Threading.Tasks.Task task, Microsoft.JSInterop.JSRuntime jsRuntime, Microsoft.JSInterop.Infrastructure.DotNetInvocationInfo invocationInfo) Line 154 C# System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread threadPoolThread, System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Line 264 C# System.Private.CoreLib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot, System.Threading.Thread threadPoolThread) Line 2349 C# System.Private.CoreLib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Line 913 C# System.Private.CoreLib.dll!System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart() Line 102 C#this error accure when I enter wrong data in any field in this code Note:ths code work good when I enter good data so i think its something in the validation this is the code with the problem that happen in I put 1 char long FirstName For example

> > @page "/addUser"
> > @rendermode InteractiveServer
> > @attribute [Authorize]
> > @using System.ComponentModel.DataAnnotations
> > @using System.Text
> > @using System.Text.Encodings.Web
> > @using BlazorAppIdentity8.Components.Account
> > @using BlazorAppIdentity8.Components.Account.Pages
> > @using Microsoft.AspNetCore.Authorization
> > @using Microsoft.AspNetCore.Identity
> > @using Microsoft.AspNetCore.WebUtilities
> > @using BlazorAppIdentity8.Data
> > @using Microsoft.EntityFrameworkCore
> > 
> > @inject UserManager<ApplicationUser> UserManager
> > @inject IUserStore<ApplicationUser> UserStore
> > @inject SignInManager<ApplicationUser> SignInManager
> > @inject IEmailSender<ApplicationUser> EmailSender
> > @inject ILogger<Register> Logger
> > @inject NavigationManager NavigationManager
> > @inject IdentityRedirectManager RedirectManager
> > @inject RoleManager<IdentityRole> roleManager
> > 
> > <AuthorizeView Roles="Admin" Context="EditContext">
> >     <Authorized>
> >         <PageTitle>Register</PageTitle>
> > 
> >         <h1>Register</h1>
> >         <EditForm Model="@Input" asp-route-returnUrl="@ReturnUrl" method="post" OnValidSubmit="RegisterUser" FormName="register1">
> >             <DataAnnotationsValidator />
> >             <h2>Create a new account.</h2>
> >             <hr />
> >             <ValidationSummary class="text-danger" role="alert" />
> >             <div class="form-floating mb-3">
> >                 <InputText @bind-Value="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
> >                 <label for="email">Email</label>
> >                 <ValidationMessage For="() => Input.Email" class="text-danger" />
> >             </div>
> >             <table>
> >                 <tbody>
> >                     <tr>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.FirstName" class="form-control" placeholder="Please enter your First Name." />
> >                                 <label for="phone-number" class="form-label">FirstName</label>
> >                                 <ValidationMessage For="() => Input.FirstName" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.LastName" class="form-control" placeholder="Please enter your Last Name." />
> >                                 <label for="phone-number" class="form-label">Last Name</label>
> >                                 <ValidationMessage For="() => Input.LastName" class="text-danger" />
> >                             </div>
> >                         </td>
> >                     </tr>
> >                     <tr>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText type="password" @bind-Value="Input.Password" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
> >                                 <label for="password">Password</label>
> >                                 <ValidationMessage For="() => Input.Password" class="text-danger" />
> >                             </div>
> >                         </td>
> > 
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText type="password" @bind-Value="Input.ConfirmPassword" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
> >                                 <label for="confirm-password">Confirm Password</label>
> >                                 <ValidationMessage For="() => Input.ConfirmPassword" class="text-danger" />
> >                             </div>
> >                         </td>
> >                     </tr>
> >                     <tr>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.PhoneNumber" class="form-control" placeholder="Please enter your phone number." />
> >                                 <label for="phone-number" class="form-label">Phone number</label>
> >                                 <ValidationMessage For="() => Input.PhoneNumber" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.OtherPhoneNumber" class="form-control" placeholder="Please enter your second phone number." />
> >                                 <label for="phone-number" class="form-label">Second Phone number</label>
> >                                 <ValidationMessage For="() => Input.OtherPhoneNumber" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputDate @bind-Value="Input.DateOfBirth" class="form-control" />
> >                                 <label for="dateofbirth">Date Of Birth</label>
> >                                 <ValidationMessage For="() => Input.DateOfBirth" class="text-danger" />
> >                             </div>
> >                         </td>
> >                     </tr>
> >                     <tr>
> >                         <td class="w-25">
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.Street" class="form-control" placeholder="Please enter your Street number." />
> >                                 <label for="phone-number" class="form-label">Street number</label>
> >                                 <ValidationMessage For="() => Input.Street" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td >
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.City" class="form-control" placeholder="Please enter your City." />
> >                                 <label for="City" class="form-label">City</label>
> >                                 <ValidationMessage For="() => Input.City" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td >
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.Province" class="form-control" placeholder="Please enter your Province." />
> >                                 <label for="Province" class="form-label">Province</label>
> >                                 <ValidationMessage For="() => Input.Province" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td class=>
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.ZipCode" class="form-control" placeholder="Please enter your ZipCode." />
> >                                 <label for="ZipCode" class="form-label">ZipCode</label>
> >                                 <ValidationMessage For="() => Input.ZipCode" class="text-danger" />
> >                             </div>
> >                         </td>
> >                         <td>
> >                             <div class="form-floating mb-3">
> >                                 <InputText @bind-Value="Input.Country" class="form-control" placeholder="Please enter your Country." />
> >                                 <label for="ZipCode" class="form-label">Country</label>
> >                                 <ValidationMessage For="() => Input.Country" class="text-danger" />
> >                             </div>
> >                         </td>
> >                     </tr>
> >                     <tr>
> >                         <td>
> >                             <input class="form-check-input" type="checkbox" id="checkbox-Customer" checked="@SelectedRolesList.Contains("Customer")" @onchange="@(e => ToggleRole("Customer"))" />
> >                             <label class="form-check-label" for="checkbox-Customer">Customer</label>
> >                             <br />
> > 
> >                             <input class="form-check-input" type="checkbox" id="checkbox-Admin" checked="@SelectedRolesList.Contains("Admin")" @onchange="@(e => ToggleRole("Admin"))" />
> >                             <label class="form-check-label" for="checkbox-Admin">Admin</label>
> >                             <br />
> > 
> >                             <input class="form-check-input" type="checkbox" id="checkbox-HR" checked="@SelectedRolesList.Contains("HR")" @onchange="@(e => ToggleRole("HR"))" />
> >                             <label class="form-check-label" for="checkbox-HR">HR</label>
> >                             <br />
> >                         </td>
> >                         <td>
> >                             <input class="form-check-input" type="checkbox" id="checkbox-Manager" checked="@SelectedRolesList.Contains("Manager")" @onchange="@(e => ToggleRole("Manager"))" />
> >                             <label class="form-check-label" for="checkbox-Manager">Manager</label>
> > 
> >                             <br />
> >                             <input class="form-check-input" type="checkbox" id="checkbox-User" checked="@SelectedRolesList.Contains("User")" @onchange="@(e => ToggleRole("User"))" />
> >                             <label class="form-check-label" for="checkbox-User">User</label>
> >                             <br />
> > 
> > 
> >                             <ValidationMessage For="() => Input.userRole" class="text-danger" />
> >                         </td>
> >                     </tr>
> >                     <tr>
> >                         <td>
> >                             <button type="submit" class="btn btn-lg btn-primary">Register</button>
> > 
> >                         </td>
> >                         <td>
> >                             <a class=" btn btn-lg btn-danger" href="/userManagement">Cancel</a>
> >                         </td>
> >                     </tr>
> > 
> >                 </tbody>
> >             </table>
> >         </EditForm>
> > 
> > 
> >     </Authorized>
> > </AuthorizeView>
> > @code {
> >     private IEnumerable<IdentityError>? identityErrors;
> > 
> >     [SupplyParameterFromForm]
> >     private InputModel Input { get; set; } = new();
> > 
> >     [SupplyParameterFromQuery]
> >     private string? ReturnUrl { get; set; }
> > 
> >     private List<string> SelectedRolesList { get; set; } = new List<string>();
> > 
> >     private string? Message => identityErrors is null ? null : $"Error: {string.Join(", ", identityErrors.Select(error => error.Description))}";
> >     private List<IdentityRole> roles = new List<IdentityRole>();
> >     protected override async Task OnInitializedAsync()
> >     {
> > 
> >         roles = await roleManager.Roles.ToListAsync();
> >         // Set the default value for Input.userRole
> >         Input.DateOfBirth = DateTime.Now;
> >     }
> >     private void ToggleRole(string role)
> >     {
> >         if (SelectedRolesList.Contains(role))
> >         {
> >             SelectedRolesList.Remove(role);
> >         }
> >         else
> >         {
> >             SelectedRolesList.Add(role);
> >         }
> >     }
> >     public async Task RegisterUser(EditContext editContext)
> >     {
> >         var user = CreateUser();
> > 
> >         await UserStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
> >         var emailStore = GetEmailStore();
> >         await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
> >         user.EmailConfirmed = true;
> >         var result = await UserManager.CreateAsync(user, Input.Password);
> > 
> >         if (!result.Succeeded)
> >         {
> >             identityErrors = result.Errors;
> >             return;
> >         }
> >         else
> >         {
> >             if (SelectedRolesList == null || SelectedRolesList.Count == 0)
> >             {
> >                 var x = await UserManager.AddToRoleAsync(user, "Customer");
> >             }
> >             else
> >             {
> >                 foreach (var selectedRole in SelectedRolesList)
> >                 {
> >                     var x = await UserManager.AddToRoleAsync(user, selectedRole);
> >                 }
> >             }
> > 
> >             // Update Input.userRole after roles have been added
> >             Input.userRole = SelectedRolesList.ToList();
> >         }
> > 
> >         //Logger.LogInformation("User created a new account with password.");
> > 
> >         NavigationManager.NavigateTo("/userManagement");
> >     }
> > 
> >     private ApplicationUser CreateUser()
> >     {
> >         try
> >         {
> >             var user = Activator.CreateInstance<ApplicationUser>();
> >             user.FirstName = Input.FirstName;
> >             user.LastName = Input.LastName;
> >             user.PhoneNumber = Input.PhoneNumber;
> >             user.OtherPhoneNumber = Input.OtherPhoneNumber;
> >             user.DateOfBirth = Input.DateOfBirth;
> >             user.Street = Input.Street;
> >             user.City = Input.City;
> >             user.Province = Input.Province;
> >             user.zipcode = Input.ZipCode;
> >             user.Country = Input.Country;
> >             // Set other properties as needed
> >             return user;
> >         }
> >         catch
> >         {
> >             throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " +
> >                 $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor.");
> >         }
> >     }
> > 
> >     private IUserEmailStore<ApplicationUser> GetEmailStore()
> >     {
> >         if (!UserManager.SupportsUserEmail)
> >         {
> >             throw new NotSupportedException("The default UI requires a user store with email support.");
> >         }
> >         return (IUserEmailStore<ApplicationUser>)UserStore;
> >     }
> > 
> >     private sealed class InputModel
> >     {
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {50} characters long.", MinimumLength = 2)]
> >         public string? FirstName { get; set; } = "";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {50} characters long.", MinimumLength = 2)]
> >         public string? LastName { get; set; } = "";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {6} and at max {50} characters long.", MinimumLength = 6)]
> >         public string? Street { get; set; } = "";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {4} and at max {50} characters long.", MinimumLength = 4)]
> >         public string? City { get; set; } ="";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {50} characters long.", MinimumLength = 2)]
> >         public string? Province { get; set; } = "";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {4} and at max {50} characters long.", MinimumLength = 4)]
> >         public string? ZipCode { get; set; } = "";
> >         [Required]
> >         [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {15} characters long.", MinimumLength = 2)]
> >         public string? Country { get; set; } = "";
> >         [Required]
> >         [Phone]
> >         [Display(Name = "OtherPhoneNumber")]
> >         public string? OtherPhoneNumber { get; set; } = "";
> >         [Required]
> >         [EmailAddress]
> >         [Display(Name = "Email")]
> >         public string Email { get; set; } = "";
> > 
> >         [Required]
> >         [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
> >         [DataType(DataType.Password)]
> >         [Display(Name = "Password")]
> >         public string Password { get; set; } = "";
> > 
> >         [DataType(DataType.Password)]
> >         [Display(Name = "Confirm password")]
> >         [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
> >         public string ConfirmPassword { get; set; } = "";
> > 
> >         [Required]
> >         [Phone]
> >         [Display(Name = "PhoneNumber")]
> >         public string PhoneNumber { get; set; } = "";
> > 
> >         [DataType(DataType.Date)]
> >         [Display(Name = "Date of birth")]
> >         public DateTime DateOfBirth { get; set; } = DateTime.Now;
> >         public List<string> userRole { get; set; } = new List<string>();
> > 
> >         //public string userRole { get; set; } = "Customer";
> >     }
> > }
> > 
> > 
> > ```

Developer technologies | .NET | Blazor
Developer technologies | .NET | Other
{count} votes

1 answer

Sort by: Most helpful
  1. ayman awadallah 30 Reputation points
    2023-12-29T22:23:46.2666667+00:00

    solved by replacing [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]

    with [MinLength(2, ErrorMessage = "The {0} must be at least {1} characters long.")] [MaxLength(50, ErrorMessage = "The {0} cannot be more than {1} characters long.")] public string? FirstName { get; set; }

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.