Is there a way to require SSL for WebApi? An attribute?
I don\'t see an applicable attribute under System.Web.Http, something like the RequireHttp
It is puzzling that there is no equivalent to the ASP.NET MVC RequireHttps attribute in ASP.NET Web API. However you can easily create one based on RequireHttps from MVC.
using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
...
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw new ArgumentNullException("actionContext");
}
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
HandleNonHttpsRequest(actionContext);
}
else
{
base.OnAuthorization(actionContext);
}
}
protected virtual void HandleNonHttpsRequest(HttpActionContext actionContext)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
actionContext.Response.ReasonPhrase = "SSL Required";
}
}
All that there is left to do is to argue about how much redundant code there is.