ASP.NET Web API-请求特定的全局变量 [英] ASP.NET Web API - Request Specific Global Variable
问题描述
当我收到一个Web API请求时,我想创建一个在请求的生命周期内每个类都可以访问的变量.我希望可以通过任何类的 App.User
之类的方式像静态属性一样访问它.但是我不希望在处理请求后将其保留,因此我猜SessionState不是一个选择.正确的方法是什么?
When I receive a Web API request, I want to create a variable that will be accessible by every class during the life-cycle of the request. I want it to be accessed like a static property in such a way as App.User
from any class. But I do not want it to be preserved after the processing of the request, so I guess SessionState is not an option. What would be the proper way to do this?
它也必须是线程安全的.
It needs to be thread-safe,too.
推荐答案
如 Igor 所述,一种选择是使用依赖项注入和参数传递,使您的全局"变量可用于需要它的所有对象.
As Igor notes, one option is to use dependency injection plus parameter passing to make your "global" variable accessible to everything that needs it.
But if you really want to use a static property, then you can use the HttpContext.Items property to stash temporary data pertaining to just the current request:
public class App
{
public static IUser User
{
get { return (IUser)HttpContext.Current.Items["User"]; }
set { HttpContext.Current.Items["User"] = value; }
}
}
A third option (which I don't recommend) is to use a static field backed by the ThreadStatic attribute:
public class App
{
[ThreadStatic]
private static IUser user;
public static IUser User
{
get { return user; }
set { user = value; }
}
}
此选项的优点是它不依赖于System.Web.但是,如果您的控制器是同步的,则它仅有效有效,并且如果您曾经使用过 async
,它将失效.
This option has the advantage that it has no dependencies on System.Web. However, it is only valid if your controller is synchronous, and it will break if you ever use async
.
这篇关于ASP.NET Web API-请求特定的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!