很抱歉,如果这是重复的问题。但是,我尝试寻找答案,但似乎找不到。
当发生特定错误时(在我的情况下,当请求太大时),ASP.NET中是否有一种重定向到页面的方法。这仅是在特定页面上发生错误时才发生,而不仅仅是在任何页面上发生。
谢谢!
答案 0 :(得分:1)
正如ADyson在评论中所说,这种情况下可能使用try - catch
块。
try
{
// put the code that you want to try here
}
catch(Exception specificException)
{
return RedirectToAction(actionName, controllerName, routeValues);
}
让我知道这是否有帮助。
答案 1 :(得分:0)
是的!如下:
在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应用程序中的错误所需的一切。您还可以根据个人喜好进行自定义。