WebApi:如何将状态从过滤器传递到控制器? [英] WebApi: how to pass state from filter to controller?

查看:150
本文介绍了WebApi:如何将状态从过滤器传递到控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在动作过滤器中提取了一些用户数据,并且可以在控制器的动作中使用其中的某些数据,但不确定如何将数据从过滤器传递到控制器.在MVC中,我可能会使用session或HttpContext.Items,但是在Web api中不可用.另一个选择是使用ThreadStatic,但是我认为必须有一个更好的解决方案?

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?

推荐答案

您可以使用 Request.Properties 字典来做到这一点.

You can use Request.Properties dictionary to do that.

在过滤器中:

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

此方法的优点是,当前请求实例在Web API管道中随处可见,因此您也可以在Formatter或MessageHandler中访问此对象.

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.

这篇关于WebApi:如何将状态从过滤器传递到控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆