本文介绍了处理在Global.asax中的ASP.NET MVC异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code这是赶上在Global.asax中所有异常

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

 protected void Application_Error(object sender, EventArgs e)
        {
            System.Web.HttpContext context = HttpContext.Current;
            System.Exception exc = context.Server.GetLastError();
            var ip = context.Request.ServerVariables["REMOTE_ADDR"];
            var url = context.Request.Url.ToString();
            var msg = exc.Message.ToString();
            var stack = exc.StackTrace.ToString();
        }

我怎样才能得到控制器名在此错误发生

How I can get controller name where this error happened

我怎样才能要求客户端的IP?

How I can get request client IP?

我可以过滤异常?我不需要404,504 .... erors

And can I filter exceptions? I dont need 404, 504.... erors

感谢

推荐答案

Global.asax中还没有概念的控制器和动作,所以我相信没有检索控制器和动作名称的API。然而,你可能会给一个尝试解决请求的网址:

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;

要得到你可以使用用户IP UserHostAddress 属性:

To get the user IP you can use UserHostAddress property:

string userIP = HttpContext.Current.Request.UserHostAddress;

要过滤掉,你是不是要处理,你可以使用像HTTP例外:

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;
    }
}

有关异常处理的最后一个的话 - 这是不这样做在全球范围内的时候有更多的本地执行它的方式是最佳做法。例如,在ASP.NET MVC基础控制器类有一个方法:

protected virtual void OnException(ExceptionContext filterContext)

其中,重写时,会给你上发生的异常的完全控制。你可以拥有一切可供您在Global.asax中的信息的 ASP.NET MVC的特定功能等来控制,鉴于情况下,路由数据等的参考。

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.

这篇关于处理在Global.asax中的ASP.NET MVC异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:24