我注意到一些我不喜欢的行为,我想知道这是否正常。
我有一个继承自 Mvc.Controller 的 BaseController,并且我有一个内部的 View 函数,它可以在每次页面加载时触发。
Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult
If Session("UserInfo") Is Nothing AndAlso User.Identity.IsAuthenticated Then
Try
ActivityMonitorService.AddActivity(UserService.GetUserByOpenID(HttpContext.User.Identity.Name).ID, _
Utilities.ActivityMonitor.Log.SessionStarted, _
Utilities.DataConverters.IPAddressToNumber(HttpContext.Request.UserHostAddress))
ActivityMonitorService.SubmitChanges()
Catch : End Try
Session("UserInfo") = UserService.GetUserByOpenID(HttpContext.User.Identity.Name)
End If
End Function
我遇到的问题是,如果会话状态已关闭,我会在此函数上收到对象引用错误
Function Edit(ByVal id As Integer) As ActionResult
If DirectCast(Session("UserInfo"), Domain.User).ID = id Then
Dim user As Domain.User = UserService.GetUserByID(id)
Return View(user)
Else
Response.StatusCode = CInt(HttpStatusCode.NotFound)
Return RedirectToAction("NotFound", "Error")
End If
End Function
现在我假设这是因为 Base FunctionView
实际上是在Return View(user)
. ActionResult
如果这是真的,我将如何连接它以在任何呼叫上触发事件?
编辑:
但是,如果我将代码放在这里,它似乎确实有效
Protected Overrides Function CreateActionInvoker() As System.Web.Mvc.IActionInvoker
If Session("UserInfo") Is Nothing AndAlso User.Identity.IsAuthenticated Then
Try
ActivityMonitorService.AddActivity(UserService.GetUserByOpenID(HttpContext.User.Identity.Name).ID, _
Utilities.ActivityMonitor.Log.SessionStarted, _
Utilities.DataConverters.IPAddressToNumber(HttpContext.Request.UserHostAddress))
ActivityMonitorService.SubmitChanges()
Catch : End Try
Session("UserInfo") = UserService.GetUserByOpenID(HttpContext.User.Identity.Name)
End If
Return MyBase.CreateActionInvoker()
End Function
这是放置会话状态“东西”的正确位置吗?