Created
December 7, 2015 13:22
-
-
Save bronumski/a208f2a3822299d48692 to your computer and use it in GitHub Desktop.
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
class HttpApiGuidlinesMiddleware : OwinMiddleware | |
{ | |
public HttpApiGuidlinesMiddleware(OwinMiddleware next) : base(next) { } | |
public override async Task Invoke(IOwinContext context) | |
{ | |
var isApiCall = context.Request.Path.StartsWithSegments(new PathString("/api")); | |
Stream originalStream = null; | |
Stream responseBuffer = null; | |
if (isApiCall) | |
{ | |
originalStream = context.Response.Body; | |
responseBuffer = new MemoryStream(); | |
context.Response.Body = responseBuffer; | |
context.Response.Headers.Append("x-request-id", Guid.NewGuid().ToString("N")); | |
} | |
await Next.Invoke(context); | |
if (isApiCall) | |
{ | |
responseBuffer.Seek(0, SeekOrigin.Begin); | |
var responseReader = new StreamReader(responseBuffer); | |
var response = await responseReader.ReadToEndAsync(); | |
using (MD5 md5 = MD5.Create()) | |
{ | |
byte[] hasedBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(response)); | |
var result = new StringBuilder(hasedBytes.Length * 2); | |
for (int i = 0; i < hasedBytes.Length; i++) | |
{ | |
result.Append(hasedBytes[i].ToString("x2")); | |
} | |
context.Response.Headers.Append("Etag", result.ToString()); | |
responseBuffer.Seek(0, SeekOrigin.Begin); | |
responseBuffer.CopyTo(originalStream); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment