Evgeni
Evgeni

Reputation: 3343

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?

Upvotes: 27

Views: 13176

Answers (1)

Filip W
Filip W

Reputation: 27187

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.

Upvotes: 63

Related Questions