检查会话对象并相应返回

时间:2016-05-09 20:53:32

标签: c# asp.net-mvc-3

我的控制器操作中有以下代码。在整个应用程序中,我有超过15个控制器和40多个操作。例如:

//Check if USER SESSION object is available
if (Session["user"] != null)
{
    return View();
}
else
{
    return RedirectToAction("logout", "Home", new { area = "Common", value = "SessionTimeOut" });
}

我不想为所有40个动作重复if语句。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:0)

您需要查看AuthenticationFilters(有关MVC演练,请参阅here。)

FTA:

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext) {

        //For demo purpose only. In real life your custom principal might be retrieved via different source. i.e context/request etc.
        filterContext.Principal = new MyCustomPrincipal(filterContext.HttpContext.User.Identity, new []{"Admin"}, "Red");
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) {
        var color = ((MyCustomPrincipal) filterContext.HttpContext.User).HairColor;
        var user = filterContext.HttpContext.User;

        if (!user.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

自由贸易协定的使用:

public class HomeController : Controller
{
    //***here is where it's applied. you can also do this globally in Global.asax if preferred***
    [CustomAuthentication]
    public ActionResult Index()
    {
        return View();
    }
}

答案 1 :(得分:0)

要补充指向[CustomAuthentication]属性的答案,您可以创建一个基本控制器类,如下所示:

[CustomAuthentication]
public class BaseController : Controller
{
}

您的15个控制器可以继承自:

public HomeController : BaseController

现在,默认情况下,派生控制器上的每个操作方法都将执行[Authorize]属性,因此对于不需要授权的操作方法,您可以使用[AllowAnonymous]属性标记它们:< / p>

public class HomeController : BaseController
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }
}