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 RequireHttps
attribute we have for MVC. I'm just trying to avoid rolling my own attribute/ message handler if there is a built in solution.
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.
All that there is left to do is to argue about how much redundant code there is.
After some research I determined this is probably the most appropriate response. It could be updated to provide json, text, or xml despite the specification indicating Html is recommended.
Here is the specification: RFC 2817
You can use the RequireHttpsHandler from WebAPIContrib project. Basically, all it does is to check the incoming request URI scheme:
Alternately, Carlos Figueira has another implementation on his MSDN blog.
you can use the following filter class to force your action method to use SSL, this will handle your request wither its a GET method or any other verb, if its a get method it will redirect the browser (using the location header) to the new URI. Otherwise a message will be shown to use https
Below code shows that you have to override OnAuthorization method after inheriting from AuthorizationFilterAttribute.
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.
Use this in Register method like this