Created
March 2, 2014 10:19
-
-
Save benfoster/9304548 to your computer and use it in GitHub Desktop.
Quick and easy OWIN pipeline hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using AppFunc = Func<IDictionary<string, object>, Task>; | |
public static class OwinPipelineHookExtensions | |
{ | |
public static IAppBuilder UseHooks( | |
this IAppBuilder app, | |
Action<IDictionary<string, object>> before = null, | |
Action<IDictionary<string, object>> after = null) | |
{ | |
return app.Use(new Func<AppFunc, AppFunc>(next => (async env => | |
{ | |
if (before != null) | |
{ | |
before.Invoke(env); | |
} | |
await next.Invoke(env); | |
if (after != null) | |
{ | |
after.Invoke(env); | |
} | |
}))); | |
} | |
public static IAppBuilder UseHooks<TState>( | |
this IAppBuilder app, | |
Func<IDictionary<string, object>, TState> before = null, | |
Action<TState, IDictionary<string, object>> after = null, | |
TState defaultState = default(TState)) | |
{ | |
return app.Use(new Func<AppFunc, AppFunc>(next => (async env => | |
{ | |
TState state = defaultState; | |
if (before != null) | |
{ | |
state = before.Invoke(env); | |
} | |
await next.Invoke(env); | |
if (after != null) | |
{ | |
after.Invoke(state, env); | |
} | |
}))); | |
} | |
public static IAppBuilder UseHooksAsync( | |
this IAppBuilder app, | |
Func<IDictionary<string, object>, Task> before = null, | |
Func<IDictionary<string, object>, Task> after = null) | |
{ | |
return app.Use(new Func<AppFunc, AppFunc>(next => (async env => | |
{ | |
if (before != null) | |
{ | |
await before.Invoke(env); | |
} | |
await next.Invoke(env); | |
if (after != null) | |
{ | |
await after.Invoke(env); | |
} | |
}))); | |
} | |
public static IAppBuilder UseHooksAsync<TState>( | |
this IAppBuilder app, | |
Func<IDictionary<string, object>, Task<TState>> before = null, | |
Func<TState, IDictionary<string, object>, Task> after = null, | |
TState defaultState = default(TState)) | |
{ | |
return app.Use(new Func<AppFunc, AppFunc>(next => (async env => | |
{ | |
TState state = defaultState; | |
if (before != null) | |
{ | |
state = await before.Invoke(env); | |
} | |
await next.Invoke(env); | |
if (after != null) | |
{ | |
await after.Invoke(state, env); | |
} | |
}))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment