我可以访问OWIN环境字典吗?

Fre*_*red 2 owin asp.net-core

我可以在ASP.NET Core中访问OWIN环境字典吗?

我想从Startup.cs文件中访问它.

我想访问它的原因是因为我想将OWIN环境字典传递给我的中间件或从我的中间件中访问它.

Fre*_*red 5

是的你可以!

首先安装Microsoft.AspNetCore.Owin包.

然后,从您获得实例的任何地方,HttpContext您都可以OwinEnvironment使用HttpContext作为构造函数的参数创建该类的实例.

var environment = new OwinEnvironment(HttpContext);
Run Code Online (Sandbox Code Playgroud)

这没有任何索引器,所以你不能这样做environment["owin.RequestProtocol"],但你可以这样做:

var requestProtocol = environment.Single(x => x.Key == Owin.RequestProtocol");
Run Code Online (Sandbox Code Playgroud)

但是,您可以.ToDictionary通过执行以下操作将其变为字典:

var dictionary = environment.ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)

现在它有一个索引器,你可以引用键environment["owin.RequestProtocol"]来获取值.

还有一个OwinFeatureCollection类可以提供环境来获取字典.

var environment = new OwinEnvironment(HttpContext);
var features = new OwinFeatureCollection(environment);
var requestProtocol = features["owin.RequestProtocol"];
Run Code Online (Sandbox Code Playgroud)

但是,OWinContext对于强类型访问器不再存在Microsoft.AspNetCore.Owin,即Microsoft.Owin在不同包中的命名空间中.