Skip to content

Instantly share code, notes, and snippets.

@karbyninc
Last active February 11, 2016 15:31
Show Gist options
  • Save karbyninc/719fbb997940c6e8f484 to your computer and use it in GitHub Desktop.
Save karbyninc/719fbb997940c6e8f484 to your computer and use it in GitHub Desktop.
Message Handlers in Web API
public class APIKeyHandler : DelegatingHandler
{
private const string REQUEST_HEADER = "X-KARBYN-APIKEY";
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isValidAPIKey = false;
//Validate that the api key exists, and if so, validate
if (request.Headers.Contains(REQUEST_HEADER))
isValidAPIKey = APIKeyService.Validate(request.Headers.GetValues(REQUEST_HEADER).First());
//If the key is not valid, return an http status code. This message could, of course, be localized using resources.
if (!isValidAPIKey)
return request.CreateResponse(HttpStatusCode.Forbidden, "Bad API Key");
//Allow the request to process further down the pipeline
var response = await base.SendAsync(request, cancellationToken);
//Return the response back up the chain
return response;
}
}
public class LoggingHandler : DelegatingHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//Log request headers and URL
var requestHeaders = request.Headers.ToDictionary(h => h.Key, h => h.Value);
string headersToLog = String.Join("rn", requestHeaders.Select(h => h.Key + ": " + String.Join(",", h.Value)));
Logger logger = new Logger();
logger.Log("Url: " + request.RequestUri + "rn---------rnrnHeaders: rn" + headersToLog + "rn------------rnrnBody: rn" + await request.Content.ReadAsStringAsync());
//Response comes back
var response = await base.SendAsync(request, cancellationToken);
//Log response
if (response.Content != null)
{
string responseMessage = await response.Content.ReadAsStringAsync();
logger.Log("Response: rn" + responseMessage);
}
//Return response
return response;
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
//Delegating Handlers
config.MessageHandlers.Add(new APIKeyHandler());
config.MessageHandlers.Add(new LoggingHandler());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment