加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – ASP MVC授权所有操作除了几个

发布时间:2020-12-15 18:48:56 所属栏目:asp.Net 来源:网络整理
导读:我有一个控制器,我想要求默认除了一对夫妇之外的所有操作的授权。因此,在下面的示例中,除Index之外,所有操作都需要认证。我不想装饰每个动作与授权,我只是想在某些情况下覆盖默认授权,可能是一个自定义过滤器,如NotAuthorize。 [Authorize]public cla
我有一个控制器,我想要求默认除了一对夫妇之外的所有操作的授权。因此,在下面的示例中,除Index之外,所有操作都需要认证。我不想装饰每个动作与授权,我只是想在某些情况下覆盖默认授权,可能是一个自定义过滤器,如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();
    }
}

解决方法

好的,这是我做的。如果有更好的方式让我知道。
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();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读