ASP.NET MVC Error Logging in Both Global.asax and Error.aspx

巧了我就是萌 提交于 2019-12-10 21:59:40

问题


I'm creating an ASP.NET MVC application. I need to handle exceptions in two places.

Global.asax.vb file:

Public Class MvcApplication
    Inherits System.Web.HttpApplication
    ...
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        LogException(HttpContext.Current.Server.GetLastError(), Request)
    End Sub
    Shared Sub LogException(ByVal ex As Exception, ByRef r As System.Web.HttpRequest)
        ...
    End Sub
End Class

Views\Shared\Error.aspx file:

<%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage(Of System.Web.Mvc.HandleErrorInfo)" %>
<script runat="server">
    Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
        MvcApplication.LogException(Model.Exception, Request)
    End Sub
</script>
...

But I get this error:

C:\inetpub\example.com\Views\Shared\Error.aspx(5): error BC30451: Name 'MvcApplication' is not declared.

Where should I define my LogException() function so that it is accessible from both the Global.asax.vb file and the Error.aspx file? Where is the most MVC-ish?


回答1:


You may want to try an module called ELMAH. Scott Hanselman says "ELMAH is Tivo for your ASP.NET Errors". I've am currently using it for logging errors in my ASP .NET + MVC applications and it works like a charm. Setup was easy because all that is required is adding lines to the web.config. You can even restrict who has access to view the error logs.

http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx




回答2:


The most MVC-ish way would be to use ActionFilters to handle (log) exceptions.

Check out this for example:

Logging with ASP.NET MVC Action Filters




回答3:


Actually for what I could gather you're only missing a directive:

<%@ Import Namespace="[Your default namespace]" %>

And it whould work as advertised.



来源:https://stackoverflow.com/questions/832046/asp-net-mvc-error-logging-in-both-global-asax-and-error-aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!