asp.net mvc中的错误处理3 [英] Error Handling in asp.net mvc 3
问题描述
这是我想要做的:
- 如果应用程序崩溃或者发生错误,它将转到特定的错误页面。
- 我可以抛出我的自己的错误从控制器动作。 (并且转到错误页面)。
我发现了以下方式:
我该如何处理这个正确的方法?
如果解决方案是类似的,或者像上面的列表中的#1,我正在使用ninject,我没有创建一个基类。
全球错误处理
所有你需要做的是更改web.config页面中的customErrors模式=开页面
错误将通过Error.cshtml显示驻留在共享文件夹中。
确保Error.cshtml Layout不为null 。
[这样可以像:@ {Layout = 〜/查看/共享/ _Layout.cshtml; }
或删除Layout =空代码块]
Error.cshtml的样例标记: -
@ {Layout =〜/ Views / Shared / _Layout.cshtml; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
< html>
< head>
< title>错误< / title>
< / head>
< body>
< h2>
抱歉,处理您的请求时发生错误。
< / h2>
< p>控制器名称:@ Model.ControllerName< / p>
< p>动作名称:@ Model.ActionName< / p>
< p>消息:@ Model.Exception.Message< / p>
< / body>
< / html>
对于特定错误处理
添加HandleError属性到控制器类中的具体操作。为该特定错误提供'查看'和'异常类型'。
示例NotImplemented异常处理程序:
code> public class MyController:Controller
{
[HandleError(View =NotImplErrorView,ExceptionType = typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException(此方法未实现);
return View();
}
}
Is there a built in or a proper way to handle errors in asp.net mvc 3?
This is what I want to do:
- If the application crashes, or throws an error, it goes to a specific error page.
- I can throw my own error from the controller action. (and it goes to an error page).
I found the following ways:
- I see there is a long way to do it here. (for v1 and v2 but also applies to v3).
- Using errorhandle attribute here.
How do I handle this the proper way?
If the solution is similar or is like #1 in the list above, I am using ninject and I have not created a base class. How do I still do this?
For Global Error Handling
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.
Make sure that Error.cshtml Layout is not null.
[It sould be something like: @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<p>Controller Name: @Model.ControllerName</p>
<p>Action Name : @Model.ActionName</p>
<p>Message: @Model.Exception.Message</p>
</body>
</html>
For Specific Error Handling
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:
public class MyController: Controller
{
[HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException("This method is not implemented.");
return View();
}
}
这篇关于asp.net mvc中的错误处理3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!