How to get access to OWIN pipeline within a FilterAttribute?

Damir Dobric Posts

Next talks:



Follow me on Twitter: #ddobric




When working with OWIN pipeline, I often have a requirement to access the pipeline within custom implementation of a filter-attribute.
For example, I want to get instance of the OwinContext like:

protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)

   protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext){

OwinContext ctx = ????


where IsAuthorized is overridable of AuthorizeAttribute, when working with authorization. To solve this you will need an initialized instance of HttpActionContext.
Usually filter methods typically provide some kind of Invoke-method, which must be implemented. In a case of Authorization this is for example method IsAuthorized .

Following code-snippet shows how to grab out the context.

OwinContext ctx = actionContext.Request.Properties["MS_OwinContext"] as OwinContext;

            if (ctx.Environment.ContainsKey(“MyKey”))


                 . . .


As you see, the context is attached as property of HttpActionContext Context instance. Once you have that one, you can traverse a list of properties attached to Environment instance, which holds everything related to the OWIN pipeline.
So, if you are implementing your logic in Attribute, traditionally you will not implement a middleware for this task. But, to keep aligned to OWIN agnostic, you will typically be required to provide some kind of configuration, which is OWIN like.
The best way to do that is to implement a simple OWIN middleware, which does nothing than inject you specific configuration in the pipeline.

Here is an example of very simple middleware, which injects custom options, which are used by previous example:

public class MyMiddleware : OwinMiddleware
public override async Task Invoke(IOwinContext context)
            context.Environment.Add(“MyKey”, new
            await m_Next.Invoke(context);


Posted May 18 2015, 09:49 AM by Damir Dobric is a .Net Community Blog powered by daenet GmbH.