With
HttpContext.Current.GetOwinContext()
I can recieve the current OwinContext in web applications.
With OwinContext.Set<T>
and OwinContext.Get<T>
I store values which should be present for a whole request.
Now I've a component which should be used inside web and console owin applications. In this component I currently don't have access to http context.
In the application I'm using threading and async features.
I also tried using the CallContext
but this seems to loose data in some scenarios.
How could I access the current OwinContext? Or is there an other context where I may play my values?
I do the below with a WebApi AuthorizationFilter, also you should also be able to do this on an MVC controller and WebApi controller context if you have middleware to support it for example app.UseWebApi(app) for WebApi.
The component must support the Owin pipeline, otherwise not sure how you will get the context from for the correct thread.
So maybe you can create your own custom
OwinMiddleware
to wireup this component using the app.Use() in your Owin startup.
More Info here
My Properties Middleware
public class PropertiesMiddleware : OwinMiddleware
{
Dictionary<string, object> _properties = null;
public PropertiesMiddleware(OwinMiddleware next, Dictionary<string, object> properties)
: base(next)
{
_properties = properties;
}
public async override Task Invoke(IOwinContext context)
{
if (_properties != null)
{
foreach (var prop in _properties)
if (context.Get<object>(prop.Key) == null)
{
context.Set<object>(prop.Key, prop.Value);
}
}
await Next.Invoke(context);
}
}
Owin StartUp configuration
public void Configuration(IAppBuilder app)
{
var properties = new Dictionary<string, object>();
properties.Add("AppName", AppName);
//pass any properties through the Owin context Environment
app.Use(typeof(PropertiesMiddleware), new object[] { properties });
}
WebApi Filter
public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext context, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
var owinContext = context.Request.GetOwinContext();
var owinEnvVars = owinContext.Environment;
var appName = owinEnvVars["AppName"];
}
Happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With