相关疑难解决方法(0)

我应该使用OwinContext的环境来保存每个请求的特定于应用程序的数据

我需要一种方法来存储每个请求的日志对象.使用HttpContext,我会将其添加到项目Dictionary中.如果我能帮助它,我不想把HttpContext带进去.下面的代码是我为Unity LifeTimeManager提出的建议,它将在OwinContext的Environment属性中存储对象,我可以使用我的Owin中间件访问它.

public class OwinContextLifetimeManager : LifetimeManager
{
    private string key = (new Guid()).ToString();
    private IDictionary<string, object> environment;

    public OwinContextLifetimeManager(IDictionary<string, object> environment)
    {
        this.environment = environment;
    }

    public override object GetValue()
    {
        if (environment != null && environment.ContainsKey(key))
            return environment[key];
        else
            return null;
    }

    public override void RemoveValue()
    {
        if (environment != null)
            environment.Remove(key);
    }

    public override void SetValue(object newValue)
    {
        if (environment != null)
            environment[key] = newValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以从我的中间件中使用它:

container.RegisterType<IRequestLog, RequestLog>(new OwinContextLifetimeManager(environment));
Run Code Online (Sandbox Code Playgroud)

在我看来,我可以选择我想要的任何键,除了那些已经由Owin保留的键.有什么理由我不应该为此目的使用OwinContext.Environment吗?MSDN文档对此的最佳实践含糊不清.

Darrel Miller在这里的回答:当使用OWIN自我主机时,我应该如何存储每个请求数据ASP.NET Web API …

c# asp.net unity-container owin owin-middleware

17
推荐指数
1
解决办法
1万
查看次数

使用 OWIN 自托管 ASP.NET Web API 时应如何存储每个请求数据

我正在将 ASP.NET Web API 从 IIS 托管转换为自托管。

在其中之一中,DelegatingHandlers我根据 HTTP 标头中的令牌设置当前用户。我一直用来HttpContext.Current.Items存储这些信息,但在自托管下不可用。

存储可在应用程序中的任何位置访问的每个请求数据的正确方法是什么?

c# asp.net-web-api owin

6
推荐指数
1
解决办法
2342
查看次数