This series of articles will describe writing WEB API with all HTTP supported verbs (i.e.) and consuming those using AJAX. Although, you can consume the API in any wbesite or application but, I will show you consumption in Dynamics 365 using AJAX calls.
In the first part of these articles, I am going to explain everything to create and use “Head” and “Options” HTTP Verbs.
Let me explain a little about “Head” and “Options”. Head is almost same like Get but there is no response body in it. This is useful when you you want to check what a Get request will return or is the Web API is currently up and running or not. An OPTIONS request can return what other HTTP verbs/methods the web API supports. This is useful to test API to avoid fatal errors.
Let’s create our empty web API project in Visual studio 2015. Right click on your solution file in VS and add new project like this
Let’s say new web API name is “StudentWebAPI”
Click “Ok”. On next screen, select these options
Add new Web API controller by right clicking on “Controllers” folder
Let’s create a new action named “IsWebAPIRunning” with Http Verb “Head”. Set RouPrefix of web API and Http supported verb on action along with route.
We can set Http verb by another way “[HttpHead]” as you can see commented code in above screen i.e. //[HttpHead].
Now create another action named “Options” with Http Verb “Options”.
Note other things you can try as commented in above code.
You can also write Options action like this
Above highlighted line of code is necessary if you want to read particular headers from response of API.
You need to be careful about one thing that you need to have only one action with Options verb otherwise the API will throw error at run time when you will call any of these two actions. I have just shown you another way to do the same thing.
Your WebAPIConfig.cs should look like this
Now, let’s run our web API, it throws error like this
Don’t worry about this error. You can test the API by this URL
http://localhost:30402/api/Student/IsWebAPIRunning
Hit this URL along with correct port as you can see above. Response comes like this
As we are using “HEAD” verb on our action “IsWebAPIRunning”. So, this is the reason it is showing this response. One thing is pretty sure by this response that our Web API is working fine.
Now in order to use the web API in another website or domain, CORS should be enabled for this. Enable CORS by adding package for CORS on the web api project using Nuget package manager.
After installing CORS, you need to enable CORS which enables web API to be accessed outside of its domain. There are different levels on which you can enable CORS i.e. On a Controller, on specific actions or on entire web API.
Enable CORS on controller
[RoutePrefix("api/Student")] [EnableCors(origins: "http://localhost:5901", headers: "*", methods: "*", exposedHeaders: "X-My-Header")] public class StudentController : ApiController Enable CORS globally in WebApiConfig.cs file var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
The constructor of class “EnableCorsAttribute” takes three arguments i.e. Origins, Headers and Methods. If you specify * in first parameter like we did then it means that this API is accessible from all external domains. If we set * for headers, it means all headers are accessible. Similarly for third parameter (i.e. Methods), use of * means this API is accessible by using all HTTP methods i.e. Get, Post, Head, Put, etc.
Here is the JS code to test both actions of Student Web API.
// JavaScript source code var serviceURL = "http://localhost:30402/api/Student/"; function isStudentsWebAPIWorking() { debugger; var postData = null; //--For "HEAD" var fullURL = serviceURL + "IsWebAPIRunning"; debugger; var isAPIWorking = false; $.ajax({ type: "HEAD", url: fullURL, async: false, success: function (jsonObject, responseStatus, response) { debugger; var statusText = response.statusText; if (statusText == "OK" && responseStatus == "success") { isAPIWorking = true; } return isAPIWorking; }, error: function (jqXHR, responseStatus, response) { debugger; //alert('Error while executing search operation.'); return isAPIWorking; } }); return isAPIWorking; } function getOptions() { debugger; var fullURL = serviceURL + 'OPTIONS'; var allowedHttpMethods = 'There is some error on getting supported verbs from web API.'; $.ajax({ url: fullURL, type: "OPTIONS", async: false, dataType: 'json', data: null, contentType: 'application/json', success: function (data, textStatus, jqXHR) { debugger; if (data != null && data != undefined) { if (data.Headers != null && data != undefined) { for (var i = 0; i < data.Headers.length; i++) { var headerAttributeKey = data.Headers[i].Key; if (headerAttributeKey == "Access-Control-Allow-Methods") { allowedHttpMethods = data.Headers[i].Value[0]; break; } } } } return allowedHttpMethods; }, error: function (jqXHR, textStatus, errorThrown) { debugger; //responseObject.Error = 'Error while executing search operation.';//jsonObject.Message; return allowedHttpMethods; } }); return allowedHttpMethods; }
References:
https://www.c-sharpcorner.com/article/enable-cors-in-asp-net-webapi-2/
https://msdn.microsoft.com/en-us/magazine/dn532203.aspx