Last active
August 29, 2015 14:25
-
-
Save jasonmitchell/d02d2b4f9216e62c92d7 to your computer and use it in GitHub Desktop.
Sample code demonstrating the basics of writing OWIN middleware. Associated blog article: http://json.codes/blog/basics-of-writing-owin-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 System.Threading.Tasks; | |
using Microsoft.Owin; | |
public class BasicMiddleware : OwinMiddleware | |
{ | |
public BasicMiddleware(OwinMiddleware next) : base(next) | |
{ | |
} | |
public async override Task Invoke(IOwinContext context) | |
{ | |
await Next.Invoke(context); | |
} | |
} |
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 System; | |
using System.Net; | |
using System.Threading.Tasks; | |
using Microsoft.Owin; | |
using Newtonsoft.Json; | |
public class BasicMiddleware : OwinMiddleware | |
{ | |
private static readonly PathString Path = new PathString("/my-middleware-url"); | |
public BasicMiddleware(OwinMiddleware next) : base(next) | |
{ | |
} | |
public async override Task Invoke(IOwinContext context) | |
{ | |
if (!context.Request.Path.Equals(Path)) | |
{ | |
await Next.Invoke(context); | |
return; | |
} | |
var responseData = new { Date = DateTime.Now }; | |
context.Response.StatusCode = (int)HttpStatusCode.OK; | |
context.Response.ContentType = "application/json"; | |
context.Response.Write(JsonConvert.SerializeObject(responseData)); | |
} | |
} |
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 static class BasicMiddlewareAppBuilderExtensions | |
{ | |
public static void UseBasicMiddleware(this IAppBuilder app) | |
{ | |
app.Use<BasicMiddleware>(); | |
} | |
} |
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 partial class Startup | |
{ | |
private void ConfigureBasicMiddleware(IAppBuilder app) | |
{ | |
app.Use<BasicMiddleware>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment