Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi: how to pass state from filter to controller?

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?

like image 453
Evgeni Avatar asked Feb 25 '13 02:02

Evgeni


People also ask

How do I use Web API filters?

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.


1 Answers

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.

like image 107
Filip W Avatar answered Nov 24 '22 12:11

Filip W