在执行(每一次)Web API操作之前执行代码 [英] Execute code before (EVERY) Web API action

查看:102
本文介绍了在执行(每一次)Web API操作之前执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API接口,我正在尝试适应多租户体系结构.以前,我们有WCF模式,通过该模式我们将参数(客户端ID)传递给服务,然后将其存储以供以后在代码中使用.这意味着客户端ID不必是传递给每个调用的第一个参数.

I have a Web API interface I'm trying to adapt to a multi-tenant architecture. Previously, we had a WCF mode whereby we passed a parameter, client ID, to the service, which then stored this for use in the code later. This meant that Client ID didn't have to be the first parameter passed to every call.

我想对Web API做同样的事情,而不是:

I'd like to do the same with Web API, i.e., rather than having:

GetDocument(int clientId, int documentId)
GetDefault(int clientId)
GetImage(int clientId, int imageId)

刚刚:

GetDocument(int documentId)
GetDefault()
GetImage(int imageId)

但是我需要一些方法来执行以下操作:

But I need some way to do the following:

  1. 从路由获取clientId
  2. 将此值放入我拥有的状态对象中

所有在调用实际执行之前.我有点想路由将被重写-路由必须包含客户端ID,而不是我的API,我觉得很好.因此,对 GetDefault 的调用可能类似于:

All before the call actually executes. I'm kind of thinking that the route will get rewritten - I'm fine with the route having to have the client id in it, just not my API. So the call to GetDefault might look like:

/Document/GetDefault/1

API是:

GetDefault()

我该如何实现?

推荐答案

一种方法是自定义ActionFilter.请参阅此处,尽管它与MVC有关概念与WebAPI相同:

One approach would be a custom ActionFilter. See here, although it's about MVC the concept is identical to WebAPI:

ASP.NET MVC提供了用于执行过滤逻辑的操作过滤器在调用动作方法之前或之后.动作筛选器是自定义属性,这些属性提供声明性的方式来添加前动作和动作后行为对控制器的动作方法的影响.

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

例如:

    public class MyActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
           //....
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
           //....
        }
    }

并使用它来装饰您的API控制器/操作:

And use that do decorate your API controllers/actions:

    [MyActionFilter]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

这篇关于在执行(每一次)Web API操作之前执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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