ASP.NET Web API-请求特定的全局变量 [英] ASP.NET Web API - Request Specific Global Variable

查看:325
本文介绍了ASP.NET Web API-请求特定的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我收到一个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屋!

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