1
我有以下兩個操作,不斷調用對方,並進入無限循環。我究竟做錯了什麼?HandleUnauthorizedRequest去InfiniteLoop
Public Overrides Sub OnAuthorization(filterContext As System.Web.Mvc.AuthorizationContext)
'This calls the AuthorzeCore function and also makes sure that the browser does not cache this function
MyBase.OnAuthorization(filterContext)
If Not IsNothing(filterContext.Result) Then
Return
End If
'Gets the calling Controller
Dim controllerName As String = filterContext.Controller.GetType().Name
'Gets the calling action
Dim actionName As String = filterContext.ActionDescriptor.ActionName
'Checks whether the logged in user has access to the action of the controller
Dim canAccess As test.Security.Permissions.PermissionTypes
canAccess = test.ApplicationSecurity.GetSecurityObject().GetAccess(controllerName & "." & actionName)
If canAccess = Security.Permissions.PermissionTypes.DISABLE Then
'User has access to the application but not to the action they are trying to access, so throw a Unauthorised exception
filterContext.HttpContext.Response.StatusCode = 403
HandleUnauthorizedRequest(filterContext)
End If
End Sub
Protected Overrides Sub HandleUnauthorizedRequest(filterContext As System.Web.Mvc.AuthorizationContext)
''To make sure that we throw a not authorised error rather not authenticated message
'If filterContext.HttpContext.Request.IsAuthenticated Then
' 'filterContext.Result = New HttpStatusCodeResult(CType(System.Net.HttpStatusCode.Forbidden, Int32))
' filterContext.Result = New RedirectToRouteResult(
'Else
' MyBase.HandleUnauthorizedRequest(filterContext)
'End If
If (filterContext.HttpContext.Request.IsAjaxRequest()) Then
Dim urlHelper As UrlHelper = New UrlHelper(filterContext.RequestContext)
filterContext.Result = New JsonResult With {.Data = New With {.Error = "NotAuthorized", .URL = urlHelper.Action("UnAuthorized", "Error")}, _
.JsonRequestBehavior = JsonRequestBehavior.AllowGet}
ElseIf filterContext.HttpContext.Response.StatusCode = 403 Then
filterContext.Result = New ViewResult With {.ViewName = "UnAuthorized"}
Else
filterContext.Result = New ViewResult With {.ViewName = "UnAuthenticated"}
End If
End Sub
如果我從onauthorisation函數中刪除handleunauthorizedrequest調用,那麼它只是忽略了我已經設置狀態碼爲403並顯示頁面。 – Baahubali 2013-05-02 02:04:58
我不確定這是否是一個好的做法,但它的工作原理,如果我添加這一行而不是在授權函數中將狀態代碼設置爲403 filterContext.Result = New ViewResult With {.ViewName =「UnAuthorized」} – Baahubali 2013-05-02 03:06:53
That isn推薦使用[HttpUnauthorizedResult](http://msdn.microsoft.com/en-us/library/system.web.mvc.httpunauthorizedresult(v = vs108).aspx)。 'filterContext.Result = new HttpUnauthorizedResult()'。 – James 2013-05-02 07:54:56