我正在为我的所有控制器实现一个类,如果用户未经过身份验证,它将重定向到登录页面。 RedirectToAction行虽然没有重定向。你能帮助纠正吗?
public class SecureController : Controller
{
public SecureController()
{
if (User == null || !User.Identity.IsAuthenticated)
{
RedirectToAction("Logon", "Account");
}
}
}
答案 0 :(得分:1)
我的建议是使用ActionFilter。这会容易得多。你可以这样做:
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// You can do any custom authentication logic in here
if (User == null || !User.Identity.IsAuthenticated)
{
// This assumes that Account is the controller, and Logon is the action method.
// You might want to check your routes if this is still not working correctly
RedirectToAction("Logon", "Account");
}
}
}
这样你就可以在你的控制器中添加一个属性,如下所示:
[RequiresAuthentication]
public ActionResult Index()
{
return View();
}
或者,正如其他人所指出的那样,如果您不需要任何自定义身份验证逻辑,则只需使用AuthorizeAttribute:
[Authorize]
public ActionResult Index()
{
return View();
}