Created
July 31, 2012 17:26
-
-
Save loudej/3218719 to your computer and use it in GitHub Desktop.
Samples of middleware
This file contains 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 AppAction = Func< | |
IDictionary<string, object>, | |
IDictionary<string, string[]>, | |
Stream, | |
Task<Tuple< | |
IDictionary<string, object>, | |
int, | |
IDictionary<string, string[]>, | |
Func<Stream, Task>>>>; | |
public static class DefaultContentType | |
{ | |
// one way you can write parameterized middleware - returns the chaining method | |
public static Func<AppAction, AppAction> Middleware(string contentType) | |
{ | |
// "next app" passed once at startup-time | |
// additional parameters passed per-call | |
return app => async (env, headers, input) => | |
{ | |
// examine/alter call parameters here | |
// call to the next app in pipeline | |
var result = await app(env, headers, input); | |
// examine/alter result parameters here | |
if (!result.Item3.ContainsKey("Content-Type")) | |
{ | |
result.Item3["Content-Type"] = new[] { contentType }; | |
} | |
return result; | |
}; | |
} | |
// can be overloaded | |
public static Func<AppAction,AppAction> Middleware() | |
{ | |
return Middleware("text/html"); | |
} | |
} |
This file contains 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
// example middleware with owin.dll reference | |
using Owin; | |
public static class BlueGreen | |
{ | |
// static method used to chain | |
public static AppDelegate Middleware(AppDelegate app) | |
{ | |
return async call => | |
{ | |
// examine and/or adjust call | |
var result = await app(call); | |
// examine and/or adjust result | |
return result; | |
} | |
} | |
// syntax sugar to give builder.UseBlueGreen() and intellisense | |
public static AppDelegate UseBlueGreen(this IAppBuilder builder) | |
{ | |
return builder.Use<AppDelegate>(Middleware); | |
} | |
} |
This file contains 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 Owin; | |
public class Startup | |
{ | |
public void Configuration(IAppBuilder builder) | |
{ | |
// use BlueGreen middleware via extension method | |
builder.UseBlueGreen(); | |
// use DefaultContentType middleware via chaining function | |
builder.Use(DefaultContentType.Middleware("text/plain")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment