Home > Software engineering >  ASP.NET Core identify give null value (identify)
ASP.NET Core identify give null value (identify)

Time:06-21

I created a class called ApplicationUser that inherits from IdentityUser, and I use that ApplicationUser in a controller to show email address in view.

Controller code:

public IActionResult test()
{
        //var claimsIdentity = (ClaimsIdentity)User.Identity;
        //var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
        //ApplicationUser x = _db.ApplicationUser.SingleOrDefault( x=>x.Id==claim.Type);

        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);// will give the user's userId
        var userName = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName
       
        // For ASP.NET Core <= 3.1
        ApplicationUser applicationUser =  _db.ApplicationUser.Find(userName);
        string userEmail = applicationUser?.Email;

        return View(applicationUser);
}

and this is view markup:

@model Store.Models.ApplicationUser

@{
    ViewData["Title"] = "test";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>test</h1>

<h1>@Model.FullName</h1>

When I run the page, I get an error

Object reference not set to an instance of an object
Model.get returned null

and the ApplicationUser returns null.

CodePudding user response:

make sure your model ApplicationUser contains property of FullName ,

in the code below

ApplicationUser applicationUser =  _db.ApplicationUser.Find(userName);
string userEmail = applicationUser?.Email;

make sure you are getting an instance of applicationUser before returning it to the view.

CodePudding user response:

Your applicationUser should not be null when you pass it to the view. You can debug to see if query result from database is null.

  • Related