简体   繁体   中英

How do I get RouteData in Application_EndRequest

I am building a simple performance logger that hooks in to Application_EndRequest / Application_BeginRequest

I would like to send my logger the name of the action and controller as some sort of key.

How can I access this information? (Don't mind if I have to intercept it earlier on and keep it around in the context)

I know this is an old question, but you can access the requested information using:

HttpContext.Current.Request.RequestContext.RouteData.Values("controller")
HttpContext.Current.Request.RequestContext.RouteData.Values("action")

Not sure that you can.

I poked around the HttpContext.Current and found that on the second (and subsequent requests), the HttpContext.Current.Items collection contains an instance of a System.Web.Routing.UrlRoutingModule.RequestData class. Unfortunately, this class is private so you can't access its data. In the debugger, however, it seems that this contains the information you're looking for (not sure why it doesn't exist on the first request though).

Alternatively, could you just use an action filter and add that to a BaseController class that all of your controllers derive from? Something like:

public class LoggingActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        var controllerName = filterContext.Controller.ControllerContext.RouteData.Values["controller"];
        var actionName = filterContext.Controller.ControllerContext.RouteData.Values["action"];
    }
}

Then create a base controller class with this attribute:

[LoggingAction]
public abstract class BaseController : Controller
{
}

This is working:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var context = new HttpContextWrapper(HttpContext.Current);
        var rd = RouteTable.Routes.GetRouteData(context);
        // use rd

    }
 object GetControllerFromContext(HttpContext context) {
        object controller = null;
        HttpContextBase currentContext = new HttpContextWrapper(context);
        UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext);
        if(routeData != null) {
            controller = routeData.Values["controller"];
        }
        return controller;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM