上位机控制器AuthorizeAttribute只是一个动作 [英] Overriding controller AuthorizeAttribute for just one action

查看:172
本文介绍了上位机控制器AuthorizeAttribute只是一个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有装饰着AuthorizeAttribute的控制器。控制器包含所有需要身份验证的除了一个动作需要由CustomAuthorizeAttribute提供了一些自定义的验证几个动作。

我的问题是,一旦我已经添加[授权]在控制器级别我可以重写它(或删除)与[CustomAuthorize]上只有一个动作?或者,我必须从控制器级别删除[授权]并单独把它添加到所有其他行动?

我问纯粹是为了方便,因为我很懒,不想装饰与AuthorizeAttribute每一个动作。

  [授权]
公共类myController的:控制器{  //需要验证
  公众的ViewResult联系(){
    返回查看();
  }  // ...有更多的动作需要身份验证  //需要自定义身份验证
  [CustomAuthorize] //从未援引为已经失败的控制器级
  公共主页的ViewResult(){
    返回查看();
  }}


解决方案

您可以更改的属性运行(使用Order属性)订单,但我认为,在这种情况下,他们仍然会都跑除非生成即日起产生。关键是要拥有在最高水平(类)应用限制最少的属性,获得方法更加严格。如果你想在首页的行动是公开的,例如,你需要删除从类的授权属性,并将其应用到各个其他方法。

如果该动作有放任的相同的水平,但有不同的结果,改变顺序可能是足够的。例如,你通常会重定向到登录的行动,但首页要重定向到关于的行动。在这方面,情况给予class属性订单= 2 首页 action属性订单= 1

I have a controller decorated with an AuthorizeAttribute. The controller contains several actions that all require authentication apart from one action that requires some custom authentication provided by CustomAuthorizeAttribute.

My question is once I've added [Authorize] at the controller level can I override it (or remove it) with [CustomAuthorize] on just one action? Or do I have to remove [Authorize] from the controller level and add it individually to every other action?

I'm asking purely for convenience because I'm lazy and don't want to decorate every action with the AuthorizeAttribute.

[Authorize]
public class MyController : Controller {

  //requires authentication
  public ViewResult Admin() {
    return View();
  }

  //... a lot more actions requiring authentication

  //requires custom authentication
  [CustomAuthorize]  //never invoked as already failed at controller level
  public ViewResult Home() {
    return View();
  }

}

解决方案

You can change the Order in which the attributes run (using the Order property), but I believe that in this case they will still both run unless one generates a result with immediate effect. The key is to have the least restrictive attribute applied at the highest level (class) and get more restrictive for the methods. If you wanted the Home action to be publicly available, for instance, you would need to remove the Authorize attribute from the class, and apply it to each of the other methods.

If the action has the same level of permissiveness, but has a different result, changing the order may be sufficient. For example, you would normally redirect to the Logon action, but for Home you want to redirect to the About action. In this, case give the class attribute Order=2 and the Home action attribute Order=1.

这篇关于上位机控制器AuthorizeAttribute只是一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆