我正在尝试保护我的登台站点(mvc5 应用程序)并且目前正在执行以下操作:
public class HomeController : Controller
{
public ActionResult Index()
{
if (Request.IsAuthenticated){
return View();
}
return RedirectToAction("Login", "Account");
}
上面的内容太费力以至于不正确,我确信我不应该用身份验证检查单独包装我的所有 View ,但我似乎无法在一个位置添加检查?
最佳答案
你应该使用 Authorize Action 过滤器:
[Authorize]
public ActionResult Index()
{
return RedirectToAction("Login", "Account");
}
您还可以在 Controller 级别使用它来确保所有操作方法都需要身份验证:
[Authorize]
public class HomeController : Controller
{
//many action methods
}
如果您想对应用程序中的每个操作方法都使用身份验证,您可以将其添加为 FilterConfig.cs 中的全局过滤器:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
如果你这样做,你必须使用 AllowAnonymous过滤登录操作,以便用户可以验证自己。
关于c# - mvc5 全局认证检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376477/