我有一个MVC控制器基类,我在其中应用了Authorize属性,因为我希望几乎所有的控制器(以及它们的操作)都被授权。
然而,我需要有一个控制器和另一个未经授权的控制器的操作。我希望能够用[Authorize(false)]
或其他东西来装饰它们,但这是不可用的。
有什么想法吗?
发布于 2012-04-25 20:16:47
似乎ASP.NET MVC4通过添加一个AllowAnonymous属性“修复”了这个问题。
David Hayden wrote about this:
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
// ...
}
// ...
}
发布于 2009-04-14 11:56:24
编辑:从ASP.NET MVC4开始,最好的方法就是使用内置的AllowAnonymous属性。
下面的答案指的是ASP.NET MVC的早期版本。
您可以使用可选的布尔参数创建一个继承自标准AuthorizeAttribute的自定义授权属性,以指定是否需要授权。
public class OptionalAuthorizeAttribute : AuthorizeAttribute
{
private readonly bool _authorize;
public OptionalAuthorizeAttribute()
{
_authorize = true;
}
public OptionalAuthorizeAttribute(bool authorize)
{
_authorize = authorize;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(!_authorize)
return true;
return base.AuthorizeCore(httpContext);
}
}
然后你可以用这个属性来装饰你的基本控制器:
[OptionalAuthorize]
public class ControllerBase : Controller
{
}
对于任何你不想要授权的控制器,只需使用带有'false‘的覆盖-例如
[OptionalAuthorize(false)]
public class TestController : ControllerBase
{
public ActionResult Index()
{
return View();
}
}
发布于 2009-05-18 07:27:17
如果你只想让一个动作在其他授权的控制器上是未经授权的,你可以这样做:
public class RequiresAuthorizationAttribute : ActionFilterAttribute
{
private readonly bool _authorize;
public RequiresAuthorizationAttribute()
{
_authorize = true;
}
public RequiresAuthorizationAttribute(bool authorize)
{
_authorize = authorize;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var overridingAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof (RequiresAuthorizationAttribute), false);
if (overridingAttributes.Length > 0 && overridingAttributes[0] as RequiresAuthorizationAttribute != null && !((RequiresAuthorizationAttribute)overridingAttributes[0])._authorize)
return;
if (_authorize)
{
//redirect if not authenticated
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//use the current url for the redirect
var redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
//send them off to the login page
//var redirectUrl = string.Format("?RedirectUrl={0}", redirectOnSuccess);
var loginUrl = LinkBuilder.BuildUrlFromExpression<HomeController>(filterContext.RequestContext, RouteTable.Routes,
x => x.Login(redirectOnSuccess));
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
}
https://stackoverflow.com/questions/746998
复制相似问题