警告:これは2009年にMVC .NET RC1用に作成されたものであり、構文的に正しくない可能性があります。
アクションフィルター属性はこれに最適です[YourAttributeName]
。コントローラーの上部にを呼び出すだけです(または、他のコントローラーが継承するアプリケーションコントローラーがある場合は、アプリケーションで1回だけ必要です)。
例えば:
namespace the_name_space
{
[Log]
public class ApplicationController : Controller
{
この時点から、この属性は、コントローラーで各アクションが実行される前に呼び出されます[Log]
。同じ方法でアクションの直前に呼び出すことにより、アクションのみでこれを指定することもできます。
OnResultExecuting
必要なロギング機能を取得するには、ほとんどの場合、とをオーバーライドする必要がありますOnResultExecuted
。どちらもかなり自明です。
例えば:
public class LogAttribute : ActionFilterAttribute
{
protected DateTime start_time;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
start_time = DateTime.Now;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
RouteData route_data = filterContext.RouteData;
TimeSpan duration = (DateTime.Now - start_time);
string controller = (string)route_data.Values["controller"];
string action = (string)route_data.Values["action"];
DateTime created_at = DateTime.Now;
//Save all your required values, including user id and whatnot here.
//The duration variable will allow you to see expensive page loads on the controller, this can be useful when clients complain about something being slow.
}
}