是否可以将方法参数传递给该方法的属性?

发布于 2024-12-08 07:12:15 字数 481 浏览 0 评论 0原文

我想创建一个自定义 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桃气十足 2024-12-15 07:12:15

不,那不是合法的 C#。

不过,您可以访问 AuthorizeAttribute 子类型内的 RouteValues

例如,在 OnAuthorization 中,您可以执行以下操作:

object id = filterContext.RouteData.Values["id"];

不过要小心。您确实需要知道自己在这里做什么。身份验证、授权和缓存之间的交互非常复杂。

No, that's not legal C#.

You can access the RouteValues inside the AuthorizeAttribute subtype, however.

Inside, e.g., OnAuthorization, you can do:

object id = filterContext.RouteData.Values["id"];

Be careful, though. You really need to know what you're doing here. The interaction between authentication, authorization, and caching is complex.

中性美 2024-12-15 07:12:15

也许 2011 年的最后一个答案对于该版本来说是正确的,但这是可能的。创建一个公共 int (或任何你需要的)并使用它。例子:

public class RestrictToTemplateManagers : AuthorizeAttribute
{
    public string GUID { get; set; }
}

[RestrictToTemplateManagers(GUID="ABC")]
public class ImportTemplatesController : Controller
{

}

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:

public class RestrictToTemplateManagers : AuthorizeAttribute
{
    public string GUID { get; set; }
}

[RestrictToTemplateManagers(GUID="ABC")]
public class ImportTemplatesController : Controller
{

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文