Skip to main content
 首页 » 编程设计

c#之重构 session 检查

2024年02月23日13powertoolsteam

我在所有 Controller 中都有这个重复代码:

        var user = Session["_User"] as User; 
 
        if (user== null) 
        { 
            return RedirectToAction("Index"); 
        } 

我该如何重构它?我应该将其添加到属性还是制作 session 包装器?

什么是最好的方法?

请您参考如下方法:

使用 MasterController 扩展您的所有 Controller 并重写 OnActionExecuting 方法,如下所示

public class MasterController : Controller 
{ 
    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        var user = Session["_User"] as User; 
 
        if (user== null) 
        { 
            if(filterContext.ActionDescriptor.ActionName != "Index" || filterContext.ActionDescriptor.ControllerDescriptor.ControllerName != "ControllerThatContainIndexAction") 
            { 
                 filterContext.Result = this.RedirectToAction("Index"); 
                 return; 
            } 
        } 
        base.OnActionExecuting(filterContext); 
    } 
}