我有一个使用 Visual Studio 2012 创建的 MVC 4 Intranet 应用程序。我使用 WindowsAuthentication 并按预期对用户进行身份验证。在某些操作中,我使用 Authorize
属性将用户限制为某些角色。当用户单击调用用户无权访问的 Controller 操作的链接时,它会弹出“需要身份验证”对话框。当我使用未经授权的帐户登录时,它会不断弹出对话框。相反,我想要这样:
- 当用户无权访问该页面时,像当前一样弹出对话框。
- 当用户输入有效但未被授权访问页面的登录名时,重定向到另一个页面,表示访问被禁止。
我该怎么做呢?作为相关信息,我使用讨论的方法自定义了角色提供程序 here
最佳答案
为此,您需要一个自定义授权来自行处理未经授权的情况。
你需要这样的方法:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
关于c# - .Net MVC 4 使用 Windows 身份验证 - 重定向未经授权的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812304/