Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Current OwinContext without using HttpContext

Tags:

c#

asp.net

owin

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?

like image 758
Boas Enkler Avatar asked Sep 10 '14 09:09

Boas Enkler


1 Answers

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!

like image 170
dynamiclynk Avatar answered Oct 01 '22 06:10

dynamiclynk