tags:

views:

199

answers:

2

I have a controller with an Authorize attribute like this:

[Authorize(Roles = "Viewer")]
public class HomeController : Controller
{
   //...
}

and my web.config has customErrors set like the following:

<customErrors mode="On">
      <error statusCode="401" redirect="notauthorized.html"/>
  </customErrors>

When I try to invoke an action on the Home controller using a non-authorized role I just get a blank page. I don't get redirected to the custom page. Any ideas?

A: 

A standard approach as far as I know is to have a simple error controller that handles incoming requests and outputs the appropriate view depending on which httpstatus code was returned... something like this:

  public class ErrorController : Controller
{

    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult Index()
    {

        //Check if the statuscode is HttpStatusCode.NotFound;
         if(Response.StatusCode == 401)
             return View("NotAuthorised");
        return View();
    }
}

and then specify a redirect action in your webconfig:

<customErrors mode="On" defaultRedirect="~/Error" />
Robban
+1  A: 

Take a look at tvanfosson's Answer from this very similar question, This is what I am doing(Thanks to tvanfosson), so now I just have to say:

[MyAuthorize(Roles="SuperAdmin",ViewName="AccessDenied")]
public class SuperAdminController : Controller
...

If the user is not in the role, they will get thew view specified by ViewName.

Note: the blank page is coming from Cassini, if you move the app to an actual IIS server you will see the 401.

KP
you mean if i move the app to IIS i should see the custom page? or i should just see the standard IIS 401 page?
Marco M.
You will see the 401.
KP