1

I'm making an ajax call and if the user is not an admin, i want to throw an error of type 401 - unauthorized and then let the web.config redirect the user to my access denied page:

    <customErrors mode="On">
  <error statusCode="500" redirect="~/InternalError.html"/>
  <error statusCode="401" redirect="~/AccessDenied.aspx"/>
</customErrors>

As you can see, i have a type 500 - internal server error to handle other errors. But when i run this code:

     if (user.Type != AppUser.UserType.SystemAdministrator)
            {
                throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized");
            }

web.config thinks a 500 is thrown and shows InternalError.htm instead of AccessDenied.aspx. How do i tell my ASP.NET application to throw a 401 instead of a 500, so the correct error page will be shown?

This is not MVC.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
BoundForGlory
  • 4,114
  • 15
  • 54
  • 81
  • possible duplicate of [How to generate an 401 error programatically in an ASP.NET page](http://stackoverflow.com/questions/217678/how-to-generate-an-401-error-programatically-in-an-asp-net-page) – Caramiriel Jun 08 '15 at 17:49
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jun 08 '15 at 17:50

1 Answers1

1

Set the Response.StatusCode instead and it will trigger the redirect.

Alternatively, you can use the below:

throw new HttpException(401, "Unauthorized");
ragerory
  • 1,360
  • 1
  • 8
  • 27
  • your answer is exactly what i'm doing and i still get the wrong error page. I'm in a static function if that helps – BoundForGlory Jun 08 '15 at 17:53
  • @BoundForGlory to be fair, you're casting to an int the HttpStatusCode, which *might* act a little different. Also, that was only one option to the answer, I provided a link on how to *set* the `Response.StatusCode` as well, which you should try out. Might be helpful to post the entire method so we can see exactly what else might be going on. It sounds like you might have a `catch` in there somewhere that is overriding the exception. – ragerory Jun 08 '15 at 17:55