除少数ASP MVC授权的所有行动 [英] ASP MVC Authorize all actions except a few
本文介绍了除少数ASP MVC授权的所有行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个控制器,我想需要授权,除了一对夫妇的所有操作在默认情况下。因此,在下面的所有行动的例子应该要求除指数认证。我不想装饰与授权的每一个动作,我只是想覆盖在某些情况下默认的授权可能与自定义过滤器,如NotAuthorize。
[授权]
公共类HomeController的:BaseController
{
[NotAuthorize]
公众的ActionResult指数()
{
//这其中不会
返回查看();
} 公众的ActionResult关于()
{
//此操作将需要授权
返回查看();
}
}
解决方案
好吧,这是我做的。如果有更好的方式让我知道。
公共类NotAuthorizeAttribute:FilterAttribute
{
//什么也不做,只是用于装饰
}公共类BaseController:控制器
{
保护覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
//检查这个动作有NotAuthorizeAttribute
[对象]属性= filterContext.ActionDescriptor.GetCustomAttributes(真);
如果(attributes.Any(一个=>一种是NotAuthorizeAttribute))返回; //必须登录
如果(!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result =新HttpUnauthorizedResult();
}
}
}
I have a controller and I would like to require Authorization for all actions by default except a couple. So in the example below all actions should require authentication except the Index. I don't want to decorate every action with the Authorize, I just want to override the default authorization in certain circumstances probably with a custom filter such as NotAuthorize.
[Authorize]
public class HomeController : BaseController
{
[NotAuthorize]
public ActionResult Index()
{
// This one wont
return View();
}
public ActionResult About()
{
// This action will require authorization
return View();
}
}
解决方案
Ok, this is what I did. If there is a better way let me know.
public class NotAuthorizeAttribute : FilterAttribute
{
// Does nothing, just used for decoration
}
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Check if this action has NotAuthorizeAttribute
object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
if (attributes.Any(a => a is NotAuthorizeAttribute)) return;
// Must login
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
这篇关于除少数ASP MVC授权的所有行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文