Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access session in partial page in asp.net core razor page?

When I login into the application then I stored my UserName in the session, But I can't access it on my partial page. I'm trying to show my login credential (UserName) on the razor partial page. What can I do?

AppUser user = m_UserSecurity.AuthenticateUserCredentials(UserLogin.LoginID, UserLogin.Password);
HttpContext.Session.SetString("UserName", user.Name);
like image 809
Mizanur Rahaman Avatar asked Jan 28 '26 09:01

Mizanur Rahaman


2 Answers

Try the below code at your razor partial view.

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor _httpContext
@{
    var userName = _httpContext.HttpContext.Session.GetString("UserName");
}

<div>
        My userName is : @userName
</div>
like image 95
sina_Islam Avatar answered Jan 29 '26 22:01

sina_Islam


The first method is to use ViewData[xxx], For example, After you setting session in your login action, You want to show the value of session in partial view in Privacy.cshtml, You can get that session in onGet() of PrivacyModel, Then use ViewData["xxx"] to save that value, Finally use @ViewData["xxx"] to get that value in your partial view.

But but I don't recommend this method, In you case, View Component is more suitable for you. Because View component has a "backend", you can use httpcontext to get the session in its "backend" directly. Please refer to this simple demo:

 public class UserViewComponent : ViewComponent
    {
       //inject httpcontext to get the session.
        private readonly IHttpContextAccessor _httpContext;
        public UserViewComponent(IHttpContextAccessor httpContext)
        {
            _httpContext = httpContext;
        }

        public IViewComponentResult Invoke()
        {
            var username = _httpContext.HttpContext.Session.GetString("UserName");
            return View("index",username);
        }

    }

View

Path: Pages\Shared\Components\User\Index.cshtml

@model string 

<h1>This is my view component</h1>
<h1>@Model</h1>

Then use this view component in your page

@await Component.InvokeAsync("User");

enter image description here

btw: Don't forget to register HttpContextAccessor in your program.cs

builder.Services.AddHttpContextAccessor();
like image 33
Xinran Shen Avatar answered Jan 29 '26 22:01

Xinran Shen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!