WebApi: how to pass state from filter to controller?

后端 未结 1 1245
小蘑菇
小蘑菇 2021-01-03 19:03

I am pulling some user data in action filter, and could use some of that data in a controller\'s action, but not exactly sure how to pass data from a filter to a controller.

相关标签:
1条回答
  • 2021-01-03 19:45

    You can use Request.Properties dictionary to do that.

    In the filter:

    MyType myObject = //initialize from somwhere
    actionContext.Request.Properties.Add("mykey", myObject);
    

    And then you can retrieve it in the controller:

    object myObject;
    Request.Properties.TryGetValue("mykey", out myObject);
    //cast to MyType
    

    The advantage of this approach is that the current request instance is available everywhere in the Web API pipeline, so you can access this object i.e. in the Formatter or MessageHandler too.

    0 讨论(0)
提交回复
热议问题