ASP.NET Web API跨请求缓存操作筛选器属性

史蒂文

我以前从未目睹过ASP.NET Web API(4.0.30506)中似乎有些奇怪的行为。

我看到的是,同一动作过滤器属性实例已通过Web API请求重用。在此属性注入依赖项的情况下,这尤其成问题,因为这些依赖项可能特定于Web请求。我知道属性最好是被动的,但我的假设是动作过滤器属性不缓存。

我搜索了描述此问题及其背后原因的任何文章,博客文章或Microsoft更改日志,但找不到任何东西。这使我想知道我的配置是否有问题导致这种情况发生。但是,事实是,我能够在一个空的新Visual Studio 2012 Web API项目中重现此问题。

我所做的是使用带有“ Web API”模板Visual Studio 2012 ASP.NET MVC 4 Web应用程序项目创建一个新的空项目它带有Web API 4.0.20710.0 NuGet软件包。之后,我添加了以下属性:

[DebuggerDisplay("{id}")]
public class TestFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute {
    private static readonly List<int> used = new List<int>();

    private static int counter;
    private readonly int id;

    public TestFilterAttribute() {
        this.id = Interlocked.Increment(ref counter);
    }

    public override void OnActionExecuting(HttpActionContext actionContext) {
        // Just for testing: I would expect this line never to throw, but it does.
        if (used.Contains(this.id)) throw new Exception("WAT?");
        used.Add(this.id);
        base.OnActionExecuting(actionContext);
    }
}

然后将此属性添加到ValuesController(默认模板的一部分):

public class ValuesController : ApiController {
    // GET api/values
    [TestFilterAttribute]
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // ...
}

现在,当我启动项目时,在浏览器中转到/ api / values并刷新该页面几次,“ WAT?” 引发异常。

这是Web API的正常行为吗?如果是,这是什么原因呢?还是我在某处错过了一些有关此更改的备忘录?这是否会使Web API属性特别不适合进行依赖项注入?还是我做错了什么?

米海·丁库列斯库(Mihai Dinculescu)

Web API建立在MVC之上,因此使用了很多功能。

属性实例的可重用性是MVC 3引入的主动缓存的一部分这意味着同一个Attribute实例很可能会与所有实例一起使用ActionsMVC管道将尽力将您的Attribute视为Singleton

由于同一Attribute 实例被重用,因此不会调用它的构造方法,id并且不会对其进行递增。例如,如果您id在内增加OnActionExecuting,那么一切都会很好。

您仍然可以用自己的工具做任何想要的事情Attribute您只需要记住,不能保证总是创建一个新实例构造函数不应该包含什么,但最初的初始化。

public TestFilterAttribute() {
    // Instance will be reused thus this will not be called for each Action
}

public override void OnActionExecuting(HttpActionContext actionContext) {
    // Called on each Action
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章