Handling exceptions in global.asax ASP.NET MVC

前端 未结 3 1319
梦如初夏
梦如初夏 2021-02-15 14:15

I have code which is catching all exceptions in Global.asax

 protected void Application_Error(object sender, EventArgs e) 
        {
            System.Web.HttpC         


        
3条回答
  •  萌比男神i
    2021-02-15 14:29

    Global.asax has not notion of controllers and actions, so I believe there is no an API for retrieving controller and action names. However you might give a try for resolving request URL:

    HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);
    UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
    RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext);
    string action = routeData.Values["action"] as string;
    string controller = routeData.Values["controller"] as string;
    

    To get the user IP you can use UserHostAddress property:

    string userIP = HttpContext.Current.Request.UserHostAddress;
    

    To filter out HTTP exceptions that you are not going to handle you can use something like:

    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
            case 504:
                return;
        }
    }
    

    One last remark about exception handling - it is not a best practice to do it at global level when there is a way to perform it more locally. For instance in ASP.NET MVC base Controller class has a method:

    protected virtual void OnException(ExceptionContext filterContext)
    

    which, when overridden, will give you full control on the occurred exception. You can have all the info that is available for you in Global.asax plus ASP.NET MVC specific features like a reference to controller, view context, route data etc.

提交回复
热议问题