Created
June 19, 2014 16:44
-
-
Save dereklawless/dce1d062d47fda13841f 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
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