简体   繁体   English

在web.config或global.asax EndRequest事件中重定向401?

[英]Redirect 401 in web.config or global.asax EndRequest event?

I have a site that is using forms authentication, but the login url is actually a page ("WinLogin.aspx") that is set to use windows authentication. 我有一个使用表单身份验证的站点,但是登录URL实际上是一个设置为使用Windows身份验证的页面(“ WinLogin.aspx”)。 That way, if the user is on our network, WinLogin.aspx captures their domain login and they can continue on into the application without having to reenter their username and password. 这样,如果用户在我们的网络上,则WinLogin.aspx会捕获其域登录名,并且他们可以继续进入应用程序而无需重新输入用户名和密码。 But if they are not logged into the domain, WinLogin.aspx gives a 401 error, which a browser would normally interpret by asking the user for their username and password to check against the domain server. 但是,如果未登录到域,则WinLogin.aspx会显示401错误,浏览器通常会通过询问用户的用户名和密码来解释该错误,以对照域服务器进行检查。

I want to redirect those 401 errors to my own custom page that gets that username and password, so I can do a true forms authentication, because some of the accounts in my application do not have a corresponding domain account. 我想将这401错误重定向到我自己的自定义页面上,该页面获取该用户名和密码,因此我可以进行真正的表单身份验证,因为应用程序中的某些帐户没有相应的域帐户。

I can do the rerouting of the 401 error in the web.config file like this: 我可以像这样在web.config文件中重新路由401错误:

    <httpErrors errorMode="Custom">
        <error statusCode="401" path="/Redirect401.aspx" />
    </httpErrors>

Or, I can do it with code in the global.asax end request handler like this: 或者,我可以使用global.asax最终请求处理程序中的代码来做到这一点:

void Application_EndRequest(object sender, System.EventArgs e)
{
    if (((Response.StatusCode == 401) && (Request.IsAuthenticated == true)))
    {
        Response.ClearContent();
        Response.Redirect("~/Redirect401.aspx");
    }
}

Is there any reason to prefer either method? 有什么理由偏爱这两种方法吗?

You'll want to use the web.config approach if your error handling is cut-n-dry and there's nothing you want to do prior to redirecting to the error page. 如果您的错误处理是反复无常的,并且在重定向到错误页面之前您不需要执行任何操作,则需要使用web.config方法。 In either case I tend to prefer catching errors in global.asax, then do some logging and then redirect to the error page, or error controller if it's an MVC app. 无论哪种情况,我都倾向于在global.asax中捕获错误,然后进行一些日志记录,然后重定向到错误页面,或者重定向到错误控制器(如果它是MVC应用程序)。 In my last app I used this exact approach in an MVC app and had the error controller actions take some action prior to returning the view. 在我的上一个应用程序中,我在MVC应用程序中使用了这种精确方法,并让错误控制器操作在返回视图之前采取了一些措施。 For example, in the case of a 401 error I had the action set a 403 error instead, so it did not force the browser to the login page. 例如,在401错误的情况下,我将操作设置为403错误,因此它没有强制浏览器进入登录页面。 So it all depends on your needs for one approach over the other. 因此,这完全取决于您对一种方法的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM