![](/img/trans.png)
[英]ASP.NET WindowsAuthentication custom 401 Unauthorized error page
[英]Custom 401 error page for ASP.NET MVC application
我創建了一個使用集成 Windows 身份驗證的 ASP.NET MVC 應用程序。 實現了以下授權邏輯:
嘗試通過 NTLM 從活動目錄獲取帳戶憑據。
顯示 Windows 身份驗證對話框,以便用戶可以提供另一個憑據:
然后我使用VictorySaber 的解決方案為應用程序添加了自定義錯誤頁面:
protected void Application_EndRequest()
{
int status = Response.StatusCode;
string actionName;
if (status >= 400 && status < 500)
{
switch (status)
{
case 401:
actionName = "Unauthorized";
break;
// Handle another client errors
default:
actionName = "BadRequest";
break;
}
}
else if (status >= 500 && status < 600)
{
switch (status)
{
case 501:
actionName = "NotImplemented";
break;
// Handle another server errors
default:
actionName = "InternalServerError";
break;
}
}
if (!String.IsNullOrEmpty(actionName))
{
Response.Clear();
var rd = new RouteData();
rd.Values["controller"] = "Errors";
rd.Values["action"] = actionName;
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
結果我的友好錯誤頁面被呈現。 但不會出現 Windows 身份驗證對話框。 如果出現 401 HTTP 狀態代碼,它會立即顯示 401 錯誤消息。 web.config文件的<httpErrors>
部分的技巧給出了相同的結果。
另外,我發現了捕獲取消對話框時應該發生的401.2 HTTP 狀態代碼的建議。 但在我的情況下,代碼永遠不會發生。
如何使用用戶友好的錯誤頁面而不是默認消息但不更改身份驗證對話框邏輯?
我需要實現以下要求:
默認情況下,僅當設置了SetStatus
標志時,服務器才會保持響應不變。 因此,有必要明確指定當 HTTP 狀態代碼為錯誤時 IIS 必須對現有響應做什么。
一種方法是在Web.config文件中配置<system.webServer>
部分的<httpErrors>
元素。 只需將existingResponse
屬性值設置為PassThrough
,以便服務器在現有響應存在時保持響應不變。
<system.webServer>
<!-- configuration settings -->
<httpErrors errorMode="Custom" existingResponse="PassThrough" />
</system.webServer>
如果服務器提示輸入 Windows 用戶帳戶憑據,則該配置會阻止錯誤頁面呈現。 對話框取消后,響應將替換為錯誤頁面。
通過HttpResponse
TrySkipIisCustomErrors
屬性禁用 IIS 自定義錯誤可以實現相同的結果。 因此,在問題代碼中添加以下行可以解決問題:
Context.Response.TrySkipIisCustomErrors = true;
注意。 由於某種原因,第二種方法在我的生產服務器上不起作用。 我認為,它需要額外的服務器設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.