我目前正在开发一个ASP.NET MVC4网站。 在该网站中,我不想让某些角色成为允许运行代码的用户。 我使用以下代码:
[Authorize(Roles = GROUP)]
public void Auth()
{
/* if user is in the domain and signed in
* and a member of the above group
* they will come here */
username = User.Identity.Name;
//Do somthing
}
这很好用,但是当用户不属于域和/或组时,它会提示输入用户名和密码。是否可以跳过提示并仅重定向该用户?
此网站在IIS 8中设置,其身份验证设置为Windows身份验证
答案 0 :(得分:3)
好吧,我会创建一个自定义授权属性并实现HandleUnauthorizedRequest方法来解决这个问题。
public class CustomAutorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// do authorization logic
// ...
return (/* isAuthorized */);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.Result = new RedirectResult(urlHelper.Action("Index", "Error"));
}
}
答案 1 :(得分:1)
使用
[Authorize(Roles = GROUP)]
[HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "ApplicationError")]
public void Auth()
{
/* if user is in the domain and signed in
* and a member of the above group
* they will come here */
username = User.Identity.Name;
//Do somthing
}
您可以在其中为未经授权的访问用户指定视图