Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created March 2, 2014 10:19
Show Gist options
  • Save benfoster/9304548 to your computer and use it in GitHub Desktop.
Save benfoster/9304548 to your computer and use it in GitHub Desktop.
Quick and easy OWIN pipeline hooks
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