【发布时间】:2015-02-06 01:28:57
【问题描述】:
我希望在 ActionFilter 中为每个 http 请求创建一个对象,并将该对象传递给控制器。到目前为止,我已经尝试过如下所示的 Request.Properties[]
public class DbReadonlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.Request.Properties["CustomObjectKey"] = new MyClass();
我还尝试将新对象直接分配给 ControllerBase 类。
public class DbReadonlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var controller = (MyControllerBase) actionContext.ControllerContext.Controller;
controller.StorageContextFactory = new MyClass();
问题在于这两种技术都没有将 MyClass 的实例传递给控制器,因为在调用控制器方法时,新的 Property["CustomObjectKey"] 在 Webapi 管道中丢失了。
控制器在调用操作过滤器 OnActionExecuting() 之后由 webapi 管道重新实例化。
断点确认 Webapi 管道在单个 http 请求期间安排以下事件流。
- 构造函数 MyControllerBase()
- MyAuthenticationFilter
- 过滤 OnActionExecuting()
- 构造函数 MyControllerBase()
- MyController.MethodA()
MyControler 的双重实例化很奇怪,但现在我正在寻找将新创建的对象从动作过滤器传递到控制器的任何技术。
Edit-1:这个问题 v1 中提到的 MyAuthorizationFilter 实际上是一个 Authentication 过滤器。仍在调查中。
解决方案:错误在另一个过滤器中。删除身份验证过滤器后,此问题中报告的问题就消失了。
【问题讨论】:
标签: asp.net-web-api action-filter