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. In MVC I'd probably use session or HttpContext.Items, but it's not available in web api. Another option is to use ThreadStatic, but I think there has to be a better solution?
Setting an Authentication Filter Like other filters, authentication filters can be applied per-controller, per-action, or globally to all Web API controllers. To apply an authentication filter to a controller, decorate the controller class with the filter attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With