0

I've found solutions for retrieving the logged in user's information for ASP.NET Core 6.0 MVC and Blazor but NOT for razor pages web apps. Am I supposed to create a controller and a startup.cs for my razor page web app OR is there another way?

Here's information on my set up...

  • ASP.NET Core 6.0 web app (razor pages, not MVC)
  • This site will be accessible from a parent site which the user will sign into using SSO so I don't need to create an identity solution; just need to retrieve the username, userid, roles they're members of & etc.
  • Hosted in IIS
  • Only users belonging to a certain role will be able to see the site; to be set in IIS
LeSteelBox
  • 415
  • 3
  • 15
  • Did you learn Razor Pages? You need write code to the `.cshtml.cs` file. And it is the same with MVC from your shared link. – Rena Jun 17 '22 at 02:59
  • I know what code-behind files are. It just seems odd to create a controller (as mentioned in the shared link) when I am not following an MVC pattern... – LeSteelBox Jun 17 '22 at 16:59
  • I tried adding IHttpContextAccessor (as noted in the shared link) to my IndexModel method and I get a "Dereference of a possibly null reference" error. This is so odd! Wish this was more clear. It's making migrating/upgrading to asp.net core 6 a pain :( – LeSteelBox Jun 17 '22 at 17:54
  • Hi @LeSteelBox, did you register the `IHttpContextAccessor` in Program.cs? – Rena Jun 20 '22 at 01:07

1 Answers1

0

In Razor Pages, both of the PageModel and Razor page itself have a User property which gives you access to the currently logged in user:

PageModel:

public void OnGet()
{
    var currentUserName = User.Identity.Name;
}

Razor Page

<p>You are logged in a @User.Identity.Name</p>
Mike Brind
  • 28,238
  • 6
  • 56
  • 88
  • Which assemblies should I use? System.Security.Principal.IPrincipal no longer seems to work with asp.net core 6.0; the app throws a "dereference of a possibly null reference error" when I use it. System.Web.Security no longer works either which I need to retrieve role information associated with a user. This post mentions how the latter is no longer supported: https://stackoverflow.com/questions/52475483/is-there-any-alternative-for-system-web-security-membershipuser-in-dotnetcore – LeSteelBox Jun 17 '22 at 17:13
  • @LeSteelBox 'dereference of a possibly null reference error' doesn't mean that it doesn't work. It is a warning that you might be referencing a null reference (which could result in a NullReferenceException). If you don't like those warnings, set `Nullable` to `disable` in the _.csproj_ file – Mike Brind Jun 20 '22 at 11:03