asp.net-mvc 如何让 ELMAH 与 ASP.NET MVC [HandleError] 属性一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/766610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
提问by dswatik
I am trying to use ELMAH to log errors in my ASP.NET MVC application, however when I use the [HandleError] attribute on my controllers ELMAH doesn't log any errors when they occur.
我正在尝试使用 ELMAH 在我的 ASP.NET MVC 应用程序中记录错误,但是当我在我的控制器上使用 [HandleError] 属性时,ELMAH 在它们发生时不会记录任何错误。
As I am guessing its because ELMAH only logs unhandled errors and the [HandleError] attribute is handling the error so thus no need to log it.
正如我猜测的那样,因为 ELMAH 只记录未处理的错误,而 [HandleError] 属性正在处理错误,因此不需要记录它。
How do I modify or how would I go about modifying the attribute so ELMAH can know that there was an error and log it..
我如何修改或我将如何修改属性,以便 ELMAH 可以知道存在错误并记录它..
Edit:Let me make sure everyone understands, I know I can modify the attribute thats not the question I'm asking... ELMAH gets bypassed when using the handleerror attribute meaning it won't see that there was an error because it was handled already by the attribute... What I am asking is there a way to make ELMAH see the error and log it even though the attribute handled it...I searched around and don't see any methods to call to force it to log the error....
编辑:让我确保每个人都理解,我知道我可以修改不是我要问的问题的属性......使用 handleerror 属性时 ELMAH 被绕过,这意味着它不会看到有错误,因为它被处理了已经通过属性......我要问的是有没有一种方法可以让 ELMAH 看到错误并记录它,即使属性处理了它......我四处搜索并没有看到任何方法可以调用来强制它记录错误....
采纳答案by Atif Aziz
You can subclass HandleErrorAttributeand override its OnExceptionmember (no need to copy) so that it logs the exception with ELMAH and only if the base implementation handles it. The minimal amount of code you need is as follows:
您可以子类化HandleErrorAttribute并覆盖其OnException成员(无需复制),以便它使用 ELMAH 记录异常,并且仅当基本实现处理它时。您需要的最少代码如下:
using System.Web.Mvc;
using Elmah;
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled)
return;
var httpContext = context.HttpContext.ApplicationInstance.Context;
var signal = ErrorSignal.FromContext(httpContext);
signal.Raise(context.Exception, httpContext);
}
}
The base implementation is invoked first, giving it a chance to mark the exception as being handled. Only then is the exception signaled. The above code is simple and may cause issues if used in an environment where the HttpContextmay not be available, such as testing. As a result, you will want code that is that is more defensive (at the cost of being slightly longer):
首先调用基本实现,使其有机会将异常标记为正在处理。只有这样才会发出异常信号。上面的代码很简单,如果在HttpContext可能不可用的环境中使用,例如测试,可能会导致问题。因此,您将需要更具防御性的代码(以稍长为代价):
using System.Web;
using System.Web.Mvc;
using Elmah;
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled // if unhandled, will be logged anyhow
|| TryRaiseErrorSignal(context) // prefer signaling, if possible
|| IsFiltered(context)) // filtered?
return;
LogException(context);
}
private static bool TryRaiseErrorSignal(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
if (httpContext == null)
return false;
var signal = ErrorSignal.FromContext(httpContext);
if (signal == null)
return false;
signal.Raise(context.Exception, httpContext);
return true;
}
private static bool IsFiltered(ExceptionContext context)
{
var config = context.HttpContext.GetSection("elmah/errorFilter")
as ErrorFilterConfiguration;
if (config == null)
return false;
var testContext = new ErrorFilterModule.AssertionHelperContext(
context.Exception,
GetHttpContextImpl(context.HttpContext));
return config.Assertion.Test(testContext);
}
private static void LogException(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
var error = new Error(context.Exception, httpContext);
ErrorLog.GetDefault(httpContext).Log(error);
}
private static HttpContext GetHttpContextImpl(HttpContextBase context)
{
return context.ApplicationInstance.Context;
}
}
This second version will try to use error signalingfrom ELMAH first, which involves the fully configured pipeline like logging, mailing, filtering and what have you. Failing that, it attempts to see whether the error should be filtered. If not, the error is simply logged. This implementation does not handle mail notifications. If the exception can be signaled then a mail will be sent if configured to do so.
第二个版本将首先尝试使用来自 ELMAH 的错误信号,这涉及完全配置的管道,如日志记录、邮件发送、过滤以及您拥有的内容。如果失败,它会尝试查看是否应该过滤错误。如果不是,则简单地记录错误。此实现不处理邮件通知。如果可以发出异常信号,则将发送邮件(如果配置为这样做)。
You may also have to take care that if multiple HandleErrorAttributeinstances are in effect then duplicate logging does not occur, but the above two examples should get your started.
您可能还需要注意,如果多个HandleErrorAttribute实例有效,则不会发生重复日志记录,但以上两个示例应该可以帮助您入门。
回答by Ivan Zlatev
Sorry, but I think the accepted answer is an overkill. All you need to do is this:
对不起,但我认为接受的答案是矫枉过正。您需要做的就是:
public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
public void OnException (ExceptionContext context)
{
// Log only handled exceptions, because all other will be caught by ELMAH anyway.
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
}
}
and then register it (order is important) in Global.asax.cs:
然后在 Global.asax.cs 中注册(顺序很重要):
public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
filters.Add(new ElmahHandledErrorLoggerFilter());
filters.Add(new HandleErrorAttribute());
}
回答by Raul Vejar
There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore)
The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler
The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events
现在 NuGet 中有一个 ELMAH.MVC 包,其中包括 Atif 改进的解决方案,以及一个处理 MVC 路由中的 elmah 接口的控制器(不再需要使用那个 axd)
该解决方案的问题(以及这里的所有问题) ) 是一种或另一种方式,elmah 错误处理程序实际上正在处理错误,忽略您可能想要设置为 customError 标记或通过 ErrorHandler 或您自己的错误处理程序的内容
恕我直言,最好的解决方案是创建一个过滤器,它将在所有其他过滤器的末尾起作用并记录已经处理过的事件。elmah 模块应该负责记录应用程序未处理的其他错误。这也将允许您使用健康监视器和可以添加到 asp.net 的所有其他模块来查看错误事件
I wrote this looking with reflector at the ErrorHandler inside elmah.mvc
我在 elmah.mvc 中的 ErrorHandler 上用反射器写了这个
public class ElmahMVCErrorFilter : IExceptionFilter
{
private static ErrorFilterConfiguration _config;
public void OnException(ExceptionContext context)
{
if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
{
var e = context.Exception;
var context2 = context.HttpContext.ApplicationInstance.Context;
//TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
{
_LogException(e, context2);
}
}
}
private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
{
if (_config == null)
{
_config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
}
var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
return _config.Assertion.Test(context2);
}
private static void _LogException(System.Exception e, System.Web.HttpContext context)
{
ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
}
private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
{
var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
if (signal == null)
{
return false;
}
signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
return true;
}
}
Now, in your filter config you want to do something like this:
现在,在您的过滤器配置中,您想要执行以下操作:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//These filters should go at the end of the pipeline, add all error handlers before
filters.Add(new ElmahMVCErrorFilter());
}
Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.
请注意,我在那里留下评论提醒人们,如果他们想添加一个实际处理异常的全局过滤器,它应该在最后一个过滤器之前进行,否则您会遇到 ElmahMVCErrorFilter 将忽略未处理的异常的情况,因为它没有被处理,它应该被 Elmah 模块记录,但是下一个过滤器将异常标记为已处理,模块忽略它,导致异常永远不会进入 elmah。
Now, make sure the appsettings for elmah in your webconfig look something like this:
现在,确保 webconfig 中 elmah 的 appsettings 看起来像这样:
<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->
The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings
这里重要的是“elmah.mvc.disableHandleErrorFilter”,如果这是假的,它将使用 elmah.mvc 中的处理程序,该处理程序将通过使用默认的 HandleErrorHandler 实际处理异常,该处理程序将忽略您的 customError 设置
This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.
这个设置允许你在类和视图中设置你自己的 ErrorHandler 标签,同时仍然通过 ElmahMVCErrorFilter 记录这些错误,通过 elmah 模块向你的 web.config 添加一个 customError 配置,甚至编写你自己的错误处理程序。您唯一需要做的就是记住不要在我们编写的 elmah 过滤器之前添加任何实际处理错误的过滤器。我忘了提及:elmah 中没有重复项。
回答by Darren
You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.
您可以采用上面的代码,通过引入一个自定义控制器工厂,将 HandleErrorWithElmah 属性注入每个控制器,更进一步。
For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.
有关更多信息,请查看我关于登录 MVC 的博客系列。第一篇文章介绍了为 MVC 设置和运行 Elmah。
There is a link to downloadable code at the end of the article. Hope that helps.
文章末尾有可下载代码的链接。希望有帮助。
回答by Ross McNab
A completely alternative solution is to not use the MVC HandleErrorAttribute, and instead rely on ASP.Net error handling, which Elmah is designed to work with.
一个完全替代的解决方案是不使用 MVC HandleErrorAttribute,而是依赖 ASP.Net 错误处理,Elmah 旨在使用它。
You need to remove the default global HandleErrorAttributefrom App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:
您需要HandleErrorAttribute从 App_Start\FilterConfig(或 Global.asax)中删除默认的全局变量,然后在您的 Web.config 中设置一个错误页面:
<customErrors mode="RemoteOnly" defaultRedirect="~/error/" />
Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Indexaction when an error occurs.
请注意,这可以是 MVC 路由 URL,因此ErrorController.Index当发生错误时,上述内容将重定向到操作。
回答by user716264
I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)
我是 ASP.NET MVC 的新手。我遇到了同样的问题,以下是我在 Erorr.vbhtml 中可行的(如果您只需要使用 Elmah 日志记录错误,它就可以工作)
@ModelType System.Web.Mvc.HandleErrorInfo
@Code
ViewData("Title") = "Error"
Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
//To log error with Elmah
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
End Code
<h2>
Sorry, an error occurred while processing your request.<br />
@item.ActionName<br />
@item.ControllerName<br />
@item.Exception.Message
</h2>
It is simply!
简直了!
回答by Komio
For me it was very important to get email logging working. After some time I discover that this need only 2 lines of code more in Atif example.
对我来说,让电子邮件记录工作非常重要。一段时间后,我发现这在 Atif 示例中只需要 2 行代码。
public class HandleErrorWithElmahAttribute : HandleErrorAttribute
{
static ElmahMVCMailModule error_mail_log = new ElmahMVCMailModule();
public override void OnException(ExceptionContext context)
{
error_mail_log.Init(HttpContext.Current.ApplicationInstance);
[...]
}
[...]
}
I hope this will help someone :)
我希望这会帮助某人:)
回答by ilmatte
This is exactly what I needed for my MVC site configuration!
这正是我的 MVC 站点配置所需要的!
I added a little modification to the OnExceptionmethod to handle multiple HandleErrorAttributeinstances, as suggested by Atif Aziz:
按照 Atif Aziz 的建议,我OnException对处理多个HandleErrorAttribute实例的方法进行了一些修改:
bear in mind that you may have to take care that if multiple
HandleErrorAttributeinstances are in effect then duplicate logging does not occur.
请记住,您可能必须注意,如果多个
HandleErrorAttribute实例有效,则不会发生重复日志记录。
I simply check context.ExceptionHandledbefore invoking the base class, just to know if someone else handled the exception before current handler.
It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.
我只是context.ExceptionHandled在调用基类之前进行检查,只是想知道其他人是否在当前处理程序之前处理了异常。
它对我有用,我发布代码以防其他人需要它并询问是否有人知道我是否忽略了任何内容。
Hope it is useful:
希望有用:
public override void OnException(ExceptionContext context)
{
bool exceptionHandledByPreviousHandler = context.ExceptionHandled;
base.OnException(context);
Exception e = context.Exception;
if (exceptionHandledByPreviousHandler
|| !context.ExceptionHandled // if unhandled, will be logged anyhow
|| RaiseErrorSignal(e) // prefer signaling, if possible
|| IsFiltered(context)) // filtered?
return;
LogException(e);
}

