【问题标题】:MVC Controller with User Access Only by Session仅通过会话进行用户访问的 MVC 控制器
【发布时间】:2014-08-08 22:12:24
【问题描述】:

我目前正在 MVC 5 中构建用户登录系统以供练习。我想做的是,只有当你有会话“UserId”时才可以访问控制器。

当然,我可以在每个动作中都写一个 if 语句,像这样:

public ActionResult Index()
{
    if (Session["UserId"] != null)
    {
        return View();
    }
    else
    {
        return RedirectToRoute("Home");
    }
}

但是有没有办法让控制器中的所有操作都实现这一点?

奖金信息: 我有 2 个控制器 - 家庭控制器 - 帐户控制器

【问题讨论】:

  • 只要是“练习”我想这很好,尽管我认为你可以练习更好的东西。最后,不要尝试真正推出自己的身份验证系统。正如您在这里的方法所证明的那样,要做到正确比您想象的要难。

标签: c# asp.net-mvc session login


【解决方案1】:

您将实现一个授权过滤器并将该过滤器应用到您的控制器。 像这样的:

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

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {            
        if (filterContext.HttpContext.Session["UserId"] == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

然后您可以将[CustomAuthentication] 属性直接应用于您的控制器,或者您可以通过控制器中的每个操作来执行此操作。像这样的:

[CustomAuthentication]//<-- If you put it here, it applies to the whole controller
public class HomeController : Controller
{
    [CustomAuthentication]//<-- Here it only applies to the Index action
    public ActionResult Index()
    {
        return View();
    }
}

【讨论】:

    【解决方案2】:

    我相信您正在寻找的是自定义 ActionFilter。 ActionFilter 中的代码可以在 ActionResult 之前执行,允许您在没有 UserId 会话的情况下重定向任何人。

    您可以这样做,而不是在每个 ActionResult 中放入代码

    [MyCustomActionFilter]
    public ActionResult Index()
    {
        return View();
    }
    

    这里有一个关于如何创建Custom Action filters in MVC的教程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 2016-03-29
      • 1970-01-01
      相关资源
      最近更新 更多