繁体   English   中英

当页面上发生特定错误时,ASP.NET重定向到页面

[英]ASP.NET redirect to a page when a specific error occurs on a page

抱歉,如果这是一个重复的问题。 但是,我尝试寻找答案,但似乎找不到。

当发生特定错误时(在我的情况下,当请求太大时),ASP.NET中是否有一种方法可以重定向到页面。 仅当错误发生在特定页面上时,而不仅仅是任何页面上才需要。

提前致谢!

正如ADyson在评论中所说,也许可以使用try - catch块来解决这种情况。

try
{
    // put the code that you want to try here
}
catch(Exception specificException)
{
    return RedirectToAction(actionName, controllerName, routeValues);
}

让我知道是否有帮助。

是! 如下:

Global.asax文件中:

protected void Application_Error(object sender, EventArgs e)
{
     Exception exception = Server.GetLastError();

     HttpException httpException = exception as HttpException;

     if (httpException != null)
     {
         if (httpException.GetHttpCode() == 404)
         {
              Server.ClearError();
              Response.Redirect("~/Home/PageNotFound");
              return;
         }
     }

     //Ignore from here if don't want to store the error in database

     HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
     RouteData routeData = RouteTable.Routes.GetRouteData(context);

     string controllerName = null;
     string actionName = null;
     if (routeData != null)
     {
         controllerName = routeData.GetRequiredString("controller");
         actionName = routeData.GetRequiredString("action");
     }


     ExceptionModel exceptionModel = new ExceptionModel()
     {
         ControllerName = controllerName ?? "Not in controller",
         ActionOrMethodName = actionName ?? "Not in Action",
         ExceptionMessage = exception.Message,
         InnerExceptionMessage = exception.InnerException != null ? exception.InnerException.Message : "No Inner exception",
         ExceptionTime = DateTime.Now
     };

     using (YourDbContext dbContext = new YourDbContext())
     {
         dbContext.Exceptions.Add(exceptionModel);
         dbContext.SaveChanges();
     }

    // Ignore till here if you don't want to store the error on database

    // clear error on server
    Server.ClearError();
    Response.Redirect("~/Home/Error");
}

然后在控制器中:

public class HomeController : Controller
{
    [AllowAnonymous]
    public ActionResult Error()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult PageNotFound()
    {
        return View();
    }
}

这是处理ASP.NET MVC应用程序中的错误所需的一切。还可以根据个人喜好进行自定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM