是否可以将方法参数传递给该方法的属性?
我想创建一个自定义 AuthorizeAttribute 类,如下所述:Override Authorize Attribute in ASP。 NET MVC。
诀窍是,用户是否被授权不仅取决于他正在执行的方法,还取决于参数:
[MyCustomAuthorize(id)]
[HttpGet]
public ActionResult File(Guid id)
{
}
基本上,用户将被授权查看某些文件,但不能查看其他文件,所以我想传递 id到我的自定义授权属性。但我似乎无法这样做,因为名称“id”不在范围内。
我知道我可以执行逻辑来确保用户可以在方法开始时访问该文件,但是我有几种方法都需要完成此操作,如果我可以将其作为[授权] 属性。
I want to make a custom AuthorizeAttribute class as described here: Override Authorize Attribute in ASP.NET MVC.
The trick is, whether or not the user is authorized depends not just on what method he is executing, but the parameter as well:
[MyCustomAuthorize(id)]
[HttpGet]
public ActionResult File(Guid id)
{
}
Basically, the user will be authorized to see some Files, but not others, so I want to pass the id to my custom authorize attribute. But I can't seem to do this because the name 'id' isn't in scope.
I know I could do the logic to make sure the user has access to that File at the beginning of the method, but I have several methods that would all need this done, and it would be much cleaner if I could do it as part of the [Authorize] attribute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,那不是合法的 C#。
不过,您可以访问
AuthorizeAttribute
子类型内的RouteValues
。例如,在
OnAuthorization
中,您可以执行以下操作:不过要小心。您确实需要知道自己在这里做什么。身份验证、授权和缓存之间的交互非常复杂。
No, that's not legal C#.
You can access the
RouteValues
inside theAuthorizeAttribute
subtype, however.Inside, e.g.,
OnAuthorization
, you can do:Be careful, though. You really need to know what you're doing here. The interaction between authentication, authorization, and caching is complex.
也许 2011 年的最后一个答案对于该版本来说是正确的,但这是可能的。创建一个公共 int (或任何你需要的)并使用它。例子:
Maybe the last answer in 2011 was correct for that version HOWEVER it is possible. Create a public int (or whatever it is you need) and use that. Example: