且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Web API-请求特定的全局变量

更新时间:2022-11-30 19:47:01

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.