What is the best way to do a redirect in an ActionFilterAttribute
. I have an ActionFilterAttribute
called IsAuthenticatedAttributeFilter
and that checked the value of a session variable. If the variable is false, I want the application to redirect to the login page. I would prefer to redirect using the route name SystemLogin
however any redirect method at this point would be fine.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- MVC-Routing,Why i can not ignore defaults,The matc
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
This works for me (asp.net core 2.1)
It sounds like you want to re-implement, or possibly extend,
AuthorizeAttribute
. If so, you should make sure that you inherit that, and notActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
There is a good question with an answer with more details here on SO.
Try the following snippet, it should be pretty clear:
Here is a solution that also takes in account if you are using Ajax requests.
Set filterContext.Result
With the route name:
You can also do something like:
If you want to use
RedirectToAction
:You could make a public
RedirectToAction
method on your controller (preferably on its base controller) that simply calls the protectedRedirectToAction
fromSystem.Web.Mvc.Controller
. Adding this method allows for a public call to yourRedirectToAction
from the filter.Then your filter would look something like:
you could inherit your controller then use it inside your action filter
inside your ActionFilterAttribute class:
inside your base controller:
Cons. of this is to change all controllers to inherit from "MyController" class