OutputCache and Logging in ASP.NET MVC 2.0
I think I might already know the answer, but here goes. I want to log when certain methods are called, but I'm torn because I've been gaining performance benefits by using the OutputCache attribute with those methods. When the method is called many times, ASP.NET MVC returns the HTML from prior calls while the cache hasn't expired开发者_C百科 and it's nice and fast. But any logging commands within that method wouldn't execute.
Is there some way for me to turn on logging to record when those methods are called, without having to remove [OutputCache] and losing the performance benefits I'm getting? Would an attribute-based logging mechanism somehow work even though the [OutputCache] attribute basically short-circuits method execution when prior output has been cached?
Thanks, Jeff
You could use the Application_BeginRequest
and Application_EndRequest
events in Global.asax
to log information before and after the action is executed. Those events will fire even for controller actions decorated with the [OutputCache]
attribute.
Darin Dimitrov is correct, use the Application_BeginRequest
and Application_EndRequest
methods.
This is how you would do it:
protected void Application_BeginRequest()
{
var routeCollection = RouteTable.Routes;
var routeData = routeCollection.GetRouteData(new HttpContextWrapper(HttpContext.Current));
// Log
Debug.WriteLine("Invoking " + routeData.Values["Controller"] + "::" + routeData.Values["Action"]);
}
protected void Application_EndRequest()
{
// Log
Debug.WriteLine("EndRequest");
}
Those methods will get called regardless if the version is served from the cache or not.
精彩评论