Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonmitchell/d02d2b4f9216e62c92d7 to your computer and use it in GitHub Desktop.
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/
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);
}
}
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));
}
}
using Owin;
public static class BasicMiddlewareAppBuilderExtensions
{
public static void UseBasicMiddleware(this IAppBuilder app)
{
app.Use<BasicMiddleware>();
}
}
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