Skip to content

Instantly share code, notes, and snippets.

@dereklawless
Created June 19, 2014 16:44
Show Gist options
  • Save dereklawless/dce1d062d47fda13841f to your computer and use it in GitHub Desktop.
Save dereklawless/dce1d062d47fda13841f to your computer and use it in GitHub Desktop.
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace App.API.Handlers
{
/// <summary>
/// A custom handler for adding an MD5 hash of the HTTP response content to the HTTP response headers.
/// </summary>
public class HttpResponseChecksumHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.Content != null)
{
response.Headers.Add("X-Checksum",
CryptographyHelper.ComputeMd5Hash(response.Content.ReadAsStringAsync().Result));
}
return task.Result;
});
}
}
}
using System.Security.Cryptography;
using System.Text;
namespace App.API.Helpers
{
/// <summary>
/// Provides utility methods for cryptographic operations.
/// </summary>
public static class CryptographyHelper
{
/// <summary>
/// Computes an MD5 hash of the specified string.
/// </summary>
/// <param name="source">The string.</param>
/// <returns>A <see cref="string"/> representing the computed hash.</returns>
public static string ComputeMd5Hash(string source)
{
if (string.IsNullOrEmpty(source))
{
return null;
}
var hash = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(source));
var sb = new StringBuilder();
for (var i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment