1

我写了以下 ActionFilterAttribute

Imports System.Web.Mvc

Namespace Mvc.Filters
    Public Class StopWatchFilter : Inherits ActionFilterAttribute
        Private tStart As DateTime
        Private tStop As DateTime

        Public Overrides Sub OnActionExecuting( _
            ByVal filterContext As ActionExecutingContext)

            tStart = DateTime.Now

        End Sub

        Public Overrides Sub OnResultExecuted( _
            ByVal filterContext As ResultExecutedContext)

            tStop = DateTime.Now
            filterContext.Controller.ViewData("StopWatch") = _
                ((tStop - tStart).TotalMilliseconds / 1000).ToString(".00")
        End Sub
    End Class
End Namespace

我在我的控制器上设置

''# Fixes SO code coloring
<MyApp.StopWatch()>
Function Index() As ActionResult
    Return View()
End Function

但是当我尝试ViewData("StopWatch")在我的视图中显示时,它只是空白。

我在这里错过了一些愚蠢的东西吗?

编辑:

似乎我可以在ViewData中设置OnActinExecuting不能OnResultExecuted.

那么,我到底如何才能制作秒表ActionFilter呢?

4

1 回答 1

2

好的,我知道了。

OnActionExecuted允许我仍然将结果写入视图,因为结果尚未执行(OnResultExecuted已经将结果执行到视图的位置)!

Imports System.Web.Mvc

Namespace Mvc.Filters
    Public Class StopWatchFilter : Inherits ActionFilterAttribute
        Private tStart As DateTime
        Private tStop As DateTime

        Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
            tStart = DateTime.Now
        End Sub

        Public Overrides Sub OnActionExecuted(ByVal filterContext As ActionExecutedContext)
            tStop = DateTime.Now
            filterContext.Controller.ViewData("StopWatch") = ((tStop - tStart).TotalMilliseconds / 1000).ToString(".00")
        End Sub
    End Class
End Namespace

基本上,如果您将上述属性附加到任何操作,并ViewData("StopWatch")在您的视图中使用。您可以看到 Controller Action 执行需要多长时间。

于 2010-12-29T18:48:24.480 回答