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
You can use the following code; (automatically redirect to https) redirect to https when an http based request is made.
To check it in visual studio you need to enable ssl in visual studio. This can be done using enable ssl property to true.
public class RequireHttpsAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if(actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
// constructing the https url
var uriBuilder = new UriBuilder(actionContext.Request.RequestUri)
{
Scheme = Uri.UriSchemeHttps,
Port = 44353 // port used in visual studio for this
};
actionContext.Response.Headers.Location = uriBuilder.Uri;
}
}
}
Use this in Register method like this
config.Filters.Add(new RequireHttpsAttribute());