In this blog, we will see how to enable a Web API service to the server over HTTPS only and not on HTTP.
If you are new to Web API, then read my earlier blogs on ASP.Net Web API here.
As you know ASP.Net Web API runs over HTTP protocol. Suppose you want to serve your Web API to be accessible only over secure HTTP i.e. HTTPS and not over HTTP.
To enable HTTPS for ASP.Net Web API, add a class in your project and inherit this class from AuthorizationFilterAttribute.
In my case, I have created a class HTTPSAttribute
public class HTTPSAttribute:AuthorizationFilterAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if(actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Found); actionContext.Response.Content = new StringContent(“<p>Use HTTPS only</p>”); } base.OnAuthorization(actionContext); } } |
Now go to your Web API Controller and add this class as an Attribute to the controller or to a specific action in that controller.
Attribute applied to the controller.
Attribute applied to an action method
[HTTPSAttribute] // GET: api/ProductMasters public IQueryable<ProductMaster> GetProductMasters() { return db.ProductMasters; } |
Now if you will request your Web API service over HTTP, you will get this message.
If you like this blog, please share this and comment below if you have any feedback.
You may like other blogs –
MVC Tutorial
Web API Tutorial
Is Angular JS different from Angular?
Interview Questions and Answers Series –
MVC Interview Questions and Answers
Web API interview questions and answers