在ASP.NET MVC中,当用户请求重定向到不可用的login.aspx页面时,可以通过在Controller中使用“RedirectToAction”方法来重定向到自定义错误页或登录页,示例代码如下所示:
public class HomeController : Controller
{
public ActionResult Index()
{
// Check if user is authenticated
if (User.Identity.IsAuthenticated)
{
// Perform some action for authenticated user
return RedirectToAction("AuthenticatedAction");
}
else
{
// Redirect to login page for unauthenticated user
return RedirectToAction("Login", "Account");
}
}
}
在以上示例中,如果用户已经通过身份验证,则会重定向到“AuthenticatedAction”方法中执行某些操作。否则,将重定向到名为“Login”的控制器中的“Account”操作,该操作将用户重定向到登录页面。
如果您想自定义错误页,则可以创建一个名为“Error.cshtml”的视图,并在Controller中使用“View”方法来指定该视图名称,示例代码如下所示:
public class HomeController : Controller
{
public ActionResult Index()
{
try
{
// Perform some action that may throw exception
throw new Exception();
}
catch (Exception ex)
{
// Log the exception
// ...
// Redirect to custom error page
return View("Error");
}
}
}
在以上示例中,如果执行某种操作时发生异常,则捕获异常并重定向到名为“Error”的自定义错误页视图。