【问题标题】:using session in MVC5 application best approach在 MVC5 应用程序中使用会话的最佳方法
【发布时间】:2017-04-01 02:20:11
【问题描述】:

我正在尝试在 asp.net mvc 5 应用程序中实现会话。该应用程序没有登录屏幕。应用程序检查访问该应用程序的用户是否存在于数据库中。 Active Director 用户名在会话中被捕获并发送到存储过程以验证用户是否存在。如果存在,我需要将 Userprofile 信息存储在会话中。我创建了一个存储库类来访问数据。我从 global.asax 中的会话启动方法调用该方法。我想验证我的实现是否正确。如果信息发生变化,如何更新会话数据。

MCRHelper

 public static string GetShortname()
        {
            string username = HttpContext.Current.User.Identity.Name;
            return username.Split('\\')[1];
        }

型号

[Serializable]
    public class UserProfileSessionData
    {
        public int UserProfileID { get; set; }
        public int EmployeeID { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string PreferredName { get; set; }
        public string DefaultLanguageCode { get; set; }
        public string DefaultCountryCode { get; set; }
        public int TimeZoneID { get; set; }
        public string TimeZoneName { get; set; }
        public string Domain { get; set; }
        public string NetworkID { get; set; }
        public string EmailAddress { get; set; }
    }

存储库类

public class SessionRespository
    {
        public List<UserProfileSessionData> GetUserProfileByNetworkId()
        {
            MCREntities db = new MCREntities();

            if (MCRHelper.UserValidate() == 1)
            {
                var userProfiles = db.spGetUserProfileByNetworkID(MCRHelper.GetShortname());
                return Mapper.Map<List<UserProfileSessionData>>(userProfiles);

            }
            return null;
        }
    }

Global.asax

  protected void Session_Start(object sender, EventArgs e)
        {
            // set SessionUtil.User here
            SessionRespository sessionRespository = new SessionRespository();
            Session["UserProfile"] = sessionRespository.GetUserProfileByNetworkId();
        }

【问题讨论】:

  • 没有登录屏幕...您如何获得有关用户的任何信息?数据模型显示:Forename、Surname、Emailadress... 要更新数据,您可以检查该数据是否已存在于 Session 对象中,如果存在:更新它,否则创建一个新条目。
  • MCRHelper.GetShortname() 有什么作用?
  • 我已经用这个方法更新了帖子。只是从字符串中获取 ntlogon 用户名
  • 这是在使用 Windows Auth 吗?
  • 用户信息在 GetShortName 方法中被捕获,该方法使用 HttpContext.Current.User.Identity.Name 获取当前主体的身份

标签: asp.net-mvc-5


【解决方案1】:

我想验证我的实现是否正确。

首先,您不应该在 Session State 中存储登录用户的信息,更不用说在 ASP.NET MVC 中尽可能不鼓励使用 Session State。

我们曾经在 15 年前的 ASP.NET Membership Provider 之前将登录的用户信息存储在 Session State 中。

由于您使用的是 ASP.NET MVC 5,因此您希望使用 ASP.NET OWIN Cookie 中间件。实施比您想象的要容易得多。

OwinAuthenticationService

private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";

public OwinAuthenticationService(HttpContextBase context)
{
    _context = context;
}

public void SignIn(User user)
{
    IList<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Sid, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.UserName),
        new Claim(ClaimTypes.GivenName, user.FirstName),
        new Claim(ClaimTypes.Surname, user.LastName),
    };

    ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignIn(identity);
}

public void SignOut()
{
    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignOut(AuthenticationType);
}

Startup.cs

您还需要配置启动以使所有这些发生。

[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

然后你就可以开始在Controller和Action方法中使用[Authorize]属性了。

[Authorize]
public class UsersController : Controller
{
   // ...
}

这里是my sample application at GitHub,它使用 AD 进行身份验证。我有用户友好的login screen,但如果你不想要它,你就不用它。

【讨论】:

  • 您能告诉我为什么使用会话不好,因为我的应用程序将在负责会话管理的负载平衡环境中运行。在我的解决方案中,我正在从数据库中读取用户配置文件信息并尝试存储在会话中。如何将这些信息存储在 cookie 中。
  • Http 是无状态的,而 ASP.NET MVC 试图保持这种状态,因为我们在维护会话状态方面存在很多问题ASP.NET Web 窗体。正如我所说,在会话状态中存储用户信息是 15 年的老方法,非常脆弱且难以维护,我们现在有更好的解决方案,例如 ASP.NET IdentityOWIN 中间件。此外,如果您使用会话状态,则无法利用 ASP.NET MVC 在授权属性中的构建。如果您以后决定迁移到 ASP.NET Core,现在可以使用 OWIN 轻松实现。
猜你喜欢
  • 2015-09-08
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多