1

I am building a job portal using ASP.NET Entity Framework. For the user management part I am using Identity. I am trying to add extra fields in the profile part of the user. Below is my ApplicationUser Model.

using Microsoft.AspNetCore.Identity;


namespace JobPortal.Models
{
    public class ApplicationUser: IdentityUser
    {
        public string? FirstName {get; set;}
        public string? LastName {get; set;}
        public string? CompanyName { get; set; }
        public string? CompanyEmail { get; set; }
        public string? CompanyContact { get; set; }
        public string? CompanyLocation { get; set; }
        public string? CompanyType { get; set; }
        public string? CompanyIndustry { get; set; }
        public DateTime? JobSeekerDateofBirth { get; set; }
        public string? JobSeekerGender { get; set; }
        public byte[]? ProfilePicture { get; set; }
    }
}

Below is the code that I have edited in the index.cshtml.cs file under Areas/Identity/Pages/Account/Manage

#nullable disable

using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using JobPortal.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace JobPortal.Areas.Identity.Pages.Account.Manage
{
    public class IndexModel : PageModel
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public IndexModel(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [TempData]
        public string StatusMessage { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [BindProperty]
        public InputModel Input { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public class InputModel
        {
            /// <summary>
            ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
            ///     directly from your code. This API may change or be removed in future releases.
            /// </summary>
            [Phone]
            [Display(Name = "Phone number")]
            public string PhoneNumber { get; set; }
#nullable enable
            public string? CompanyName { get; set; } = null;
#nullable enable
            public string? CompanyEmail { get; set; } = null;
#nullable enable
            public string? CompanyContact { get; set; } = null;
#nullable enable
            public string? CompanyLocation { get; set; } = null;
#nullable enable
            public string? CompanyType { get; set; } = null;
#nullable enable
            public string? CompanyIndustry { get; set; } = null;
#nullable enable
            public DateTime? JobSeekerDateofBirth { get; set; } = null;
#nullable enable
            public string? JobSeekerGender { get; set; } = null;
        }

        private async Task LoadAsync(ApplicationUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);
            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;


            Input = new InputModel
            {
                CompanyName = user.CompanyName, 
                CompanyEmail = user.CompanyEmail, 
                CompanyContact = user.CompanyContact, 
                CompanyLocation = user.CompanyLocation, 
                CompanyType = user.CompanyType, 
                CompanyIndustry = user.CompanyIndustry, 
                JobSeekerDateofBirth = (DateTime)user.JobSeekerDateofBirth,
                JobSeekerGender = user.JobSeekerGender,
                PhoneNumber = phoneNumber
            };
        }

        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            await LoadAsync(user);
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!ModelState.IsValid)
            {
                await LoadAsync(user);
                return Page();
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
                if (!setPhoneResult.Succeeded)
                {
                    StatusMessage = "Unexpected error when trying to set phone number.";
                    return RedirectToPage();
                }
            }

            await _signInManager.RefreshSignInAsync(user);
            StatusMessage = "Your profile has been updated";
            return RedirectToPage();
        }
    }
}

The error that I am getting is as below:

System.Nullable<T>.get_Value()
JobPortal.Areas.Identity.Pages.Account.Manage.IndexModel.LoadAsync(ApplicationUser user) in Index.cshtml.cs
+
            Input = new InputModel
JobPortal.Areas.Identity.Pages.Account.Manage.IndexModel.OnGetAsync() in Index.cshtml.cs
+
            await LoadAsync(user);
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+GenericTaskHandlerMethod.Convert<T>(object taskAsObject)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+GenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

What I expected to happen is that it will run properly as I wanted users to fill in their profile right after registering (which means after login also). But now when I click on the User manage button on the top right I get the error stated above. How do I solve it?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Gurtej Singh
  • 13
  • 1
  • 3
  • Remove `JobSeekerDateofBirth = (DateTime)user.JobSeekerDateofBirth,` and then try adding `if (user.JobSeekerDateofBirth.HasValue) { Input.JobSeekerDateofBirth = user.JobSeekerDateofBirth.Value; }` – Vivek Nuna Jul 01 '23 at 12:07
  • Your controller already has the user name which is part of the authentication. If you want the username see following : https://stackoverflow.com/questions/36641338/how-to-get-current-user-in-asp-net-core – jdweng Jul 01 '23 at 14:55

0 Answers0