WebApi:如何将状态从过滤器传递到控制器?

编程入门 行业动态 更新时间:2024-10-09 06:20:41
本文介绍了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:如何将状态从过滤器传递到控制器?

本文发布于:2023-11-16 11:00:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   如何将   控制器   状态   WebApi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!