How to use HttpContext or Claims in __Layout.cshtml?

mc 3,641 Reputation points
2023-01-27T07:05:48.23+00:00

I am using asp.net core 7.0 how to get UserClaims in Pages/Shared/_Layout.cshtml ?

I do not want to use ViewData because I have to set it in each page.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,133 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,240 questions
0 comments No comments
{count} votes

Accepted answer
  1. JasonPan - MSFT 4,201 Reputation points Microsoft Vendor
    2023-01-27T09:53:01.0766667+00:00

    Hi @打玻璃,

    You can refer the code below.

    @using Microsoft.AspNetCore.Http;
    @inject IHttpContextAccessor HttpContextAccessor;
    
    @{
        string? connectionId = HttpContextAccessor?.HttpContext?.Connection.Id;
        var Claims = HttpContextAccessor.HttpContext.User.Claims;
    }
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    .................
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Jason

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Guy Hitchman 5 Reputation points
    2023-07-08T20:26:10.3933333+00:00

    Thanks Jason. I am new to Razor Pages and web development in general. So I am sure there are lots of issues with the following as this is just a learning exercise for me. But your suggestion worked. I managed to access the session data in the _Layout.cshtml file by adding:

    builder.Services.AddHttpContextAccessor();
    

    to the services section of the Program.cs file and the following to the top of the _Layout.cshtml file:

    @using Microsoft.AspNetCore.Http;
    @inject IHttpContextAccessor HttpContextAccessor;
    @{
        string loggedIn = HttpContextAccessor.HttpContext.Session.GetString("LoggedIn") ?? "false";
    }
    
    1 person found this answer helpful.
    0 comments No comments