gpt4 book ai didi

asp.net-web-api - 在 Asp.net Web Api 授权过滤器上,如何访问参数?

转载 作者:行者123 更新时间:2023-12-03 23:22:02 25 4
gpt4 key购买 nike

我从 Asp.Net Web API 开始,这是我的问题:

我实现了一个自定义授权过滤器来检查我的消息头以查找 API key 。基于此 API key ,我检索了我的用户,然后我想看看他是否可以访问某些资源。我要检查的资源 ID 在 HTTP 请求的参数上。但是当我使用 AuthorizationFilter 方法时,操作参数列表是空的。

我怎样才能做到这一点 ?

如果我使用 ActionFilter 代替授权过滤器,我如何确定这将是第一个执行的过滤器?在全局范围内,如何指定过滤器的执行顺序?

最后一个问题,是否可以在“管道上”添加一些我可以在任何过滤器上检索的数据?类似于 session 存储但仅限于请求的东西?

感谢您的任何回复

最佳答案

授权属性在参数绑定(bind)运行之前运行,因此您不能(如您所见)使用 ActionArguments收藏。相反,您需要将请求 uri 用于查询参数,并将路由数据用于 uri 参数,如下所示。

//request at http://localhost/api/foo/id?MyValue=1
public class MyAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
//will not work as parameter binding has not yet run
object value;
actionContext.ActionArguments.TryGetValue("id", out value);

//Will get you the resource id assuming a default route like /api/foo/{id}
var routeData = actionContext.Request.GetRouteData();
var myId = routeData.Values["id"] as string;

//uri is still accessible so use this to get query params
var queryString = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
var myQueryParam = queryString["MyValue"];

//and so on
}
}

关于执行令 :

使用 FilterScope Enumeration 指定过滤器的执行顺序有 3 种不同的方法。 ...范围是全局、 Controller 和操作。 AuthoriseAttribute是“全局性的”,因此它

Specifies an action before Controller.



如果您需要在这 3 个范围内指定执行顺序,那么您应该阅读 this blog article在这里您需要实现 FilterProvider
向管道添加一些数据 :

对请求使用属性集合,此集合在请求期间可用。

    protected override bool IsAuthorized(HttpActionContext actionContext)
{
actionContext.Request.Properties.Add("__MYKEY__","MyValue");

//access this later in the controller or other action filters using
var value = actionContext.Request.Properties["__MYKEY__"];

}

关于asp.net-web-api - 在 Asp.net Web Api 授权过滤器上,如何访问参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16053732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com