Skip to content

Instantly share code, notes, and snippets.

@DForshner
Created July 27, 2013 14:23
Show Gist options
  • Save DForshner/6095009 to your computer and use it in GitHub Desktop.
Save DForshner/6095009 to your computer and use it in GitHub Desktop.
A Web API filter that requires requests to be HTTPS.
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Infrastructure
{
/// <summary>
/// A Web API filter that requires requests to be HTTPS.
/// Setup as a filter in the WebAPIConfig (Ex: config.Filters.Add(new RequireHttpsAttribute());)
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var request = actionContext.Request;
// If request uses https do nothing
if (request.RequestUri.Scheme == Uri.UriSchemeHttps)
return;
// Built return URI
UriBuilder uri = new UriBuilder(request.RequestUri);
uri.Scheme = Uri.UriSchemeHttps;
uri.Port = 443;
string body = string.Format("<p>The resource can be found at <a href=\"{0}\">{0}</a>.</p>", uri.Uri.AbsoluteUri);
// Set the appropriate resource can no be found response.
HttpResponseMessage response;
if (request.Method.Equals(HttpMethod.Get) || request.Method.Equals(HttpMethod.Head))
{
response = request.CreateResponse(HttpStatusCode.Found);
response.Headers.Location = uri.Uri;
if (request.Method.Equals(HttpMethod.Get))
{
response.Content = new StringContent(body, Encoding.UTF8, "text/html");
}
}
else
{
response = request.CreateResponse(HttpStatusCode.NotFound);
response.Content = new StringContent(body, Encoding.UTF8, "text/html");
}
actionContext.Response = response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment