簡體   English   中英

ASP.NET Core 會話狀態

[英]ASP.NET Core Session State

我有一個控制器,我有幾種方法。 在登錄方法中,如果登錄成功,我會啟動一個HttpContext.Session.SetInt32("ID") 這個 ID 是登錄用戶的 ID。我在許多其他方法中使用這個 ID 來做更多的計算和查詢。 在每種方法中,我都必須聲明一個像?int userId = HttpContext.Session.GetINT32("ID")這樣的變量才能在該方法中使用這個變量。

如何在不使用HttpContext.Session.GetInt32語句的情況下以一種可以在其他 Action 方法中使用它的方式全局聲明它。 我只是想使用 DRY 原則,以便我的代碼更清晰。

任何幫助,將不勝感激?

public class HomeController : Controller
{
    private readonly DataContext _context;
    private readonly IRepository _repo;

    public HomeController(DataContext context, IRepository repo)
    {
        this._context = context;
        this._repo = repo;
    }

    public int GetUserId()
    {
       return (int)HttpContext.Session.GetInt32("ID");
    }

如果您使用的是Identity ,那么您可以像這樣獲取用戶 ID:

User.Identity.GetUserId(); // <-- this is inside controller

在 ASP.NET Core 中管理會話(全局)的最佳方法是:

1)。 添加靜態類 SessionExtensions.cs

       public static class SessionExtensions
        {
            public static void SetObject(this ISession session, string key, object value)
            {
                session.SetString(key, JsonConvert.SerializeObject(value));
            }

            public static T GetObject<T>(this ISession session, string key)
            {
                var value = session.GetString(key);
                return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
            }

            public static void SetBoolean(this ISession session, string key, bool value)
            {
                session.Set(key, BitConverter.GetBytes(value));
            }

            public static bool? GetBoolean(this ISession session, string key)
            {
                var data = session.Get(key);
                if (data == null)
                {
                    return null;
                }
                return BitConverter.ToBoolean(data, 0);
            }

            public static void SetDouble(this ISession session, string key, double value)
            {
                session.Set(key, BitConverter.GetBytes(value));
            }

            public static double? GetDouble(this ISession session, string key)
            {
                var data = session.Get(key);
                if (data == null)
                {
                    return null;
                }
                return BitConverter.ToDouble(data, 0);
            }
        }

2)。 添加靜態類 UserSession.cs

    public static class UserSession
        {
            private static IHttpContextAccessor _accessor;
            public static void Configure(IHttpContextAccessor httpContextAccessor)
            {
                _accessor = httpContextAccessor;
            }

            public static HttpContext HttpContext => _accessor.HttpContext;


            public static Guid UserId
            {
                get
                {
                    if (HttpContext.Session.GetString("UserId") == null || Guid.Parse(HttpContext.Session.GetString("UserId")) == Guid.Empty)
                        return Guid.Empty;
                    else
                        return Guid.Parse(Convert.ToString(HttpContext.Session.GetString("UserId")));
                }
                set
                {
                    HttpContext.Session.SetString("UserId", Convert.ToString(value));
                }
            }


            public static byte[] ProfileImage
            {
                get
                {
                    if (HttpContext.Session.GetObject<byte[]>("ProfileImage") == null)
                        return null;
                    else
                        return HttpContext.Session.GetObject<byte[]>("ProfileImage");
                }
                set
                {
                    HttpContext.Session.SetObject("ProfileImage", value);
                }
            }

            public static string JwtToken
            {
                get
                {
                    if (HttpContext.Session.GetString("JwtToken") == null)
                        return null;
                    else
                        return HttpContext.Session.GetString("JwtToken");
                }
                set
                {
                    HttpContext.Session.SetString("JwtToken", value);
                }
            }

            public static string FirstName
            {
                get
                {
                    if (HttpContext.Session.GetString("FirstName") == null)
                        return null;
                    else
                        return HttpContext.Session.GetString("FirstName");
                }
                set
                {
                    HttpContext.Session.SetString("FirstName", value);
                }
            }

            public static string LastName
            {
                get
                {
                    if (HttpContext.Session.GetString("LastName") == null)
                        return null;
                    else
                        return HttpContext.Session.GetString("LastName");
                }
                set
                {
                    HttpContext.Session.SetString("LastName", value);
                }
            }

            public static string FullName { get { return (!string.IsNullOrWhiteSpace(FirstName) ? FirstName : string.Empty) + " " + (!string.IsNullOrWhiteSpace(LastName) ? LastName : string.Empty); } }


            public static string Email
            {
                get
                {
                    if (HttpContext.Session.GetString("Email") == null)
                        return null;
                    else
                        return HttpContext.Session.GetString("Email");
                }
                set
                {
                    HttpContext.Session.SetString("Email", value);
                }
            }
        }

3).在startup.cs中添加

     public void ConfigureServices(IServiceCollection services)
    {
     services.AddSession(options =>
                {
                    options.IdleTimeout = TimeSpan.FromMinutes(60);//You can set Time   
                });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSession();

        UserSession.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
    }

4)。 瞧。 完畢

--------------------
How to use :

Set session (Ex:Set session for UserId) > UserSession.UserId = 1;
Get session (int id = UserSession.UserId)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM