While using mvc intranet template with domain authorization, how can I redirect to some certain error page on authorization failure depending on the controller?
So, I have a controller class:
[AuthorizeWithRedirect(Users = @"user")]
public class MyController : Controller
{
...
}
By default I’m not redirected anywhere. I see only a blank page, if I open the page under another user. The issue is that I want the request to be redirected to different pages for different controllers if the authorization fails. That is, one page for MyController, another page for other controller, etc.
I know I could derive from AuthorizeAttribute and override HandleUnauthorizedRequest method. But I can’t make it work:
public class AuthorizeWithRedirect : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
UrlHelper urlHelper = new UrlHelper(context.RequestContext);
context.Result = new RedirectResult(urlHelper.Action("MyErrorPage"));
}
}
I get an error, saying that the specified url is not found, while MyErrorPage.cshtml does present in the Views\Shared folder.
EDIT
[Authorize(Users = @"user")]//should be redirected to ErrorPage1
public class MyController1 : Controller
{
...
}
while
[Authorize(Users = @"user")]//should be redirected to ErrorPage2
public class MyController2 : Controller
{
...
}
That is, different error pages for different controllers on one and the same authorization failure
The AuthorizeWithRedirect looks good.
But MVC is complaining that you do not have right action method.
The view is not an issue here. The controller and action method is.
Try something like this:
With present TestController with an public action method Redirect.