可以在 ASP.NET MVC 的控制器中编写以下代码:
public class HomeController : Controller
{
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
return View();
}
else
{
return RedirectToAction("Login", "Account");
}
}
}
在此代码中,我们检查用户是否已通过身份验证。如果是,则显示主页视图;否则,将重定向到登录页面。请注意,此方法假定我们的登录控制器名为“Account”,登录视图名为“Login”。
可以在应用程序的全局.asax文件中,使用以下代码注册它:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login");
}
}
}
}
此代码将在每个请求处理过程中检查用户是否已登录,如果用户未登录,则将其重定向到登录页面。