Redirect Authorization failure in mvc

2019-05-21 20:27发布

问题:

I have been doing this research for 2 days now, but i cant seem to find the answer.

How to redirect user to a specific page This is what I have now:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Member/LogOn" timeout="2880" />
</authentication>

What i want to do is if user isn't authenticated redirect to this url: ~/Account/Member/LogOn" but if the user is already authenticated but not authorized, I want to redirect to this url: ~/Account/Member/Unauthorized"

Is there anyway to do this without creating a custom authentication attribute?'

Thanks

回答1:

You can make a base controller class and override OnActionExecuting method and then inherit that controller. See following reference for details.

How to redirect from OnActionExecuting in Base Controller?



回答2:

The above code works with the [Authorize] attribute so that if the user doens't match the Authorize criteria or not authenticiated then they are bounced to the loginUrl Url.

For example,

[Authorize] just checks that they are authenticated.

[Authorize(User="User1")] and [Authorize(Roles="Manager")] both require authentication and to match the authorization criteria specified.

However, I don't think you can redirect differently for each.