[英]How do I get RouteData in Application_EndRequest
I am building a simple performance logger that hooks in to Application_EndRequest
/ Application_BeginRequest
我正在构建一个简单的性能记录器,该记录器挂接到
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. 我戳了一下
HttpContext.Current
,发现在第二个(以及后续请求)上, HttpContext.Current.Items
集合包含System.Web.Routing.UrlRoutingModule.RequestData
类的实例。 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? 另外,您是否可以仅使用一个动作过滤器并将其添加到所有控制器派生自的BaseController类中? 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.