Is there any programmatic way that where I can mandate the HTTPS in my ASP.Net Web API? I need to perform this for all HTTP methods in my Web API.

Can we mandate HTTPS to specific HTTP messages as well ?

Please note that I need to do this in programmatic way in my ASP.Net back end.


Unless I'm misunderstanding your question, wouldn't you be able to just create a RequireHttpsAttribute (inherit from ActionFilter) that does this, and decorate your controllers/actions with it?

Inside that, check the uri scheme of the request and disallow the request returning forbidden if it doesn't match the right scheme.


I don't think you can do this in your backend. You can however look at HSTS which will do that for you.


You will need to configure it in IIS

  • 2
    HSTS or any http-to-https redirect is a bad practice for an API: if the developer mistakenly use http instead of https, an automatic redirect will hide that error, and the API credentials will leak! If the http version of the API systematically answer an error, that kind of mistake can be avoided. – Tom Jan 23 '17 at 12:48

I think @Jake is looking for a programmatic solution here rather than a configuration update. It is better if you block your request in the back end if it is not coming through TLS channel.

What you can do is, create a custom filter class which inherited from the ActionFilterAttribute class. Then you can override the OnActionExecuting method to cater your requirement. You can check the request against the Uri.UriSchemeHttps and perform an appropriate action.

Following is a sample code(Please note that I am giving this as an example. It may not suitable 100% for your production environment).

public class MyHttpsOnlyFilter : ActionFilterAttribute
    public override void OnActionExecuting(HttpActionContext context)
    var request = context.Request;
    if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        var response = request.CreateResponse(HttpStatusCode.Forbidden);
        response.Content = new StringContent("This API accepts only HTTPS requests");
        context.Response = response;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.