简体   繁体   English

在AuthorizeAttribute和Controller之间传递对象

[英]Passing objects between AuthorizeAttribute and Controller

To authorize a GET request for an item by Id, I query for the item in a custom AuthorizeAttribute to verify the authenticated user has access. 要通过ID授权某项的GET请求,我在自定义AuthorizeAttribute查询该项,以验证通过身份验证的用户具有访问权限。 To prevent duplicating the query in the ApiController action, I want to pass the object from the AuthorizeAttribute to the action. 为了避免在ApiController操作中重复查询,我想将对象从AuthorizeAttribute传递给操作。

Since the AuthorizeAttribute is called in the pipeline before the ActionArgument binders have run, I cannot pass the object via HttpActionContext.ActionArguments . 由于在运行ActionArgument绑定程序之前在管道中调用了AuthorizeAttribute ,所以我无法通过HttpActionContext.ActionArguments传递对象。 I am also wary of serializing it into a querystring and potentially running up against the length limit. 我也很警惕将其序列化为查询字符串,并可能遇到长度限制。

One option for passing the item is stashing it in HttpContext.Current.Items and casting it upon retrieval in the action. 传递项目的一种方法是将其存储在HttpContext.Current.Items ,并在检索操作时将其强制转换。 I have read that this will work even in asynchronous actions, but there seems to be considerable advice against using the Items dictionary. 我已经读过,即使在异步操作中也可以使用,但是似乎有很多建议反对使用Items字典。

Should I simply re-query for the item in the action? 我是否应该简单地重新查询动作中的项目? Is using the Items dictionary appropriate? 使用Items字典合适吗? Is it appropriate to use an ActionFilterAttribute for this purpose to allow for access to HttpActionContext.ActionArguments even though I am using it for authorization? 为此目的使用ActionFilterAttribute来允许访问HttpActionContext.ActionArguments是否合适,即使我将其用于授权也是如此? Is there another vector that I have overlooked? 还有我忽略的另一个媒介吗?

I use this code 我用这个代码

 protected override bool AuthorizeCore(System.Web.Http.Controllers.HttpActionContext actionContext)
            {
                BaseApiController baseApi = actionContext.ControllerContext.Controller as BaseApiController;
                baseApi.Property = 10;
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM