开发者

In C#, how to redirect users to an access denied error aspx page?

I have a web application on C#, I have specified some security to allow only 3 users to enter the site:

<authentication mode="Windows"/>
<authorization>
    <allow users="DOMAIN\john,DOMAIN\mary,DOMAIN\jesus" />
    <deny users="*" />
</authorization>

It seems that the permission works since they can enter but people with other logons cannot enter (this is ok).

The problem now is ho开发者_JAVA百科w to catch the 401.2 error, without touching IIS, to intercept the Access is denied error and redirect the user to a user-friendly aspx page.

I tried to add some code on global.asasx Application_OnError but it doesn't work.

How can I redirect user to a errors subfolder like /errors/AccessDenied.aspx page when they are not authorized?


Add custom error section in your web.config like

<customErrors mode="On" defaultRedirect="/ErrorPages/AppError.html">
    <error statusCode="401" redirect="/ErrorPages/401-2.html" />
</customErrors>

IF that doesn't workout you can try adding the following code in your Global.asax

PrivateSub Global_EndRequest(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMyBase.EndRequest
If Response.StatusCode = 401 AndAlso Request.IsAuthenticated = TrueThen
Response.ClearContent()
Server.Execute("~/ErrorPages/401-2.html")
EndIf
EndSub


This question may be old but I found it when trying to solve the same problem in MVC. If I may just expand on @JuniorMayhe's final solution, I hope this helps somebody else.

For my project I edited the Global.asax file to redirect to a route I had created for 401 errors, sending the user to the "Unauthorised to see this" view.

In the Global.asax (as he says above, but this uses MVC's routes):

    void Application_EndRequest(object sender, System.EventArgs e)
    {
        // If the user is not authorised to see this page or access this function, send them to the error page.
        if (Response.StatusCode == 401)
        {
            Response.ClearContent();
            Response.RedirectToRoute("ErrorHandler", (RouteTable.Routes["ErrorHandler"] as Route).Defaults);
        }
    }

and in the Route.config:

        routes.MapRoute(
        "ErrorHandler",
        "Error/{action}/{errMsg}",
        new { controller = "Error", action = "Unauthorised", errMsg = UrlParameter.Optional }
        );

and in the controller:

    public ViewResult Unauthorised()
    {
        //Response.StatusCode = 401; // Do not set this or else you get a redirect loop
        return View();
    }


You could insert the location tag, to tell the aplication that the erros folders have authorization.

  <location path="errors">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜