asp.net mvc 3 中的错误处理 [英] Error Handling in asp.net mvc 3
问题描述
在 asp.net mvc 3 中是否有内置或正确的方法来处理错误?
Is there a built in or a proper way to handle errors in asp.net mvc 3?
这就是我想要做的:
- 如果应用程序崩溃或抛出错误,它会转到特定的错误页面.
- 我可以从控制器操作中抛出我自己的错误.(然后转到错误页面).
我找到了以下方法:
- 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?
如果解决方案与上面列表中的#1 类似或类似,我正在使用 ninject 并且我还没有创建基类.我该怎么做?
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?
推荐答案
用于全局错误处理
您所要做的就是更改 web.config 页面中的 customErrors mode="On"
错误将通过 Error.cshtml 显示在共享文件夹中.
确保 Error.cshtml Layout 不为 null.
[它应该是这样的:@{ Layout = "~/Views/Shared/_Layout.cshtml";}
或移除 Layout=null 代码块]
Error.cshtml 的示例标记:-
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>
对于特定的错误处理
将 HandleError 属性添加到控制器类中的特定操作.为该特定错误提供视图"和异常类型".
NotImplemented Exception Handler 示例:
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屋!