如何管理MVC中的登录会话变量

时间:2017-11-26 11:56:20

标签: design-patterns model-view-controller session-variables

我在网上搜索包括SO但无法找到问题的最佳解决方案。我接管了一个MVC项目,该项目有大约15个控制器,每个控制器类都以这两行开头:

int userid = (int)System.Web.HttpContext.Current.Session["UserID"]; string usertype = (string)System.Web.HttpContext.Current.Session["UserType"];

Code Snapshot

然后通过控制器操作方法使用这两个变量(userid,usertype)。

避免这种情况的最佳方法是什么?我找到的两个选项是创建一个SessionEndAttribute类并将其添加到每个控制器中,或者使用会话检查创建一个基本控制器类,并使所有控制器类继承自BaseController类。

这就是我现在所做的,让我知道这是否正确

控制器:

[SessionExpire]
public class WordShareController : Controller
{

    int userid = 0;
    string usertype = string.Empty;

    public WordShareController() : this(new SessionManagement())
    {

    }
    public WordShareController(SessionManagement objSession)
    {
        userid = objSession.UserId;
        usertype = objSession.UserType;

    }

SessionManagement.cs

public class SessionManagement
{
    private int _userId = 0;
    private String _userType, _userName, _webName = string.Empty;

    public SessionManagement()
    {
        if (HttpContext.Current.Session["UserID"] != null)
        {
            _userId = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
            _userType = Convert.ToString(HttpContext.Current.Session["UserType"]);
            _userName = Convert.ToString(HttpContext.Current.Session["UserName"]);
            _webName = Convert.ToString(HttpContext.Current.Session["WebName"]);
        }
    }

    public int UserId
    {
        get
        {
            return _userId;
        }
    }
    public string UserType
    {
        get
        {
            return _userType;
        }
    }
    public string UserName
    {
        get
        {
            return _userName;
        }
    }
    public string WebName
    {
        get
        {
            return _webName;
        }
    }

}

SessionExpireAttribute.cs

public class SessionExpireAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpSessionStateBase session = filterContext.HttpContext.Session;
        // If the browser session or authentication session has expired...
        if (session.IsNewSession || session["LoginUser"] == null)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                // For AJAX requests, return result as a simple string, 
                // and inform calling JavaScript code that a user should be redirected.
                JsonResult result = new JsonResult()
                {
                    Data = "SessionTimeout",
                    ContentType = "text/html"
                };
                filterContext.Result = result;
            }
            else
            {
                // For round-trip requests,
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
            { "Controller", "User" },
            { "Action", "Login" }
                });
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

1 个答案:

答案 0 :(得分:0)

另一种方法是您可以创建一个单独的类并实现mvc AuthorizeAttribute类。然后你可以在App_Start中注册这个类 - > FiletrConfig.cs

代码如下所示:

public class Authenticate : AuthorizeAttribute
{
    protected override bool AuthorizeCore(System.Web.HttpContextBase httpcontext)
    {
        //your authentication code from session or query string
    }
}

在FilterConfig.cs中,您可以像这样

注册此Authenticate类
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new Authenticate());
    }
}