When you have created a Restful API using the ASP.NET Web API and if your API is in one domain and the UI is in another domain then you might get errors due to cross-domain issues.

  1. http://localhost:5000/api/ 404 (Not Found).

  2. http://localhost:5000/api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54317' is therefore not allowed access. The response had HTTP status code 404.

In other words you cannot make a call to the WebAPI via your front end that is hosted on a different domain.

Then you can resolve it using Web API Cross Handler, you need to add a WepAPICrossHandler.cs code in the App_Start folder and register this code in Application_Start().
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Net.Http;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Net;
  9. namespace WebAPI
  10. {
  11. public class WepAPICrossHandler : DelegatingHandler
  12. {
  13. const string Origin = "Origin";
  14. const string AccessControlRequestMethod = "Access-Control-Request-Method";
  15. const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
  16. const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
  17. const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
  18. const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
  19. protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  20. {
  21. bool isCorsRequest = request.Headers.Contains(Origin);
  22. bool isPreflightRequest = request.Method == HttpMethod.Options;
  23. if (isCorsRequest)
  24. {
  25. if (isPreflightRequest)
  26. {
  27. HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
  28. response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
  29. string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
  30. if (accessControlRequestMethod != null)
  31. {
  32. response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
  33. }
  34. string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
  35. if (!string.IsNullOrEmpty(requestedHeaders))
  36. {
  37. response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
  38. }
  39. TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
  40. tcs.SetResult(response);
  41. return tcs.Task;
  42. }
  43. else
  44. {
  45. return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
  46. {
  47. HttpResponseMessage resp = t.Result;
  48. resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
  49. return resp;
  50. });
  51. }
  52. }
  53. else
  54. {
  55. return base.SendAsync(request, cancellationToken);
  56. }
  57. }
  58. }
  59. }
For using this code you need to make the following change in the Application_Start() method in the Global.asax.cs file.
  1. GlobalConfiguration.Configuration.MessageHandlers.Add(new WepAPICrossHandler());
After then we will add controller on our UI (front-end) side. Suppose we have added a HomeController.cs.
  1. public class HomeController : ApiController
  2. {
  3. public string GetEmployeeInformation(string JSONString)
  4. {
  5. var seriptSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
  6. Employee employee = seriptSerialization.Deserialize<Employee>(JSONString);
  7. //if list then we can use like this
  8. //List<Employee> employee = seriptSerialization.Deserialize<List<Employee>>(JSONString);
  9. return employee.EmployeeName;
  10. }
  11. public string PostSubmitdata([FromBody]Employee emp)
  12. {
  13. return emp.EmployeeName;
  14. }
  15. }
If you have found there is something error like : The type or namespace 'Script' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
Then you have to add references for System.Web.Extensions.dll
And the Employee class:
  1. public class Employee
  2. {
  3. public string EmployeeName { get; set; }
  4. public EmployeeDetails empdetails { get; set; }
  5. }
  6. public class EmployeeDetails
  7. {
  8. public string email { get; set; }
  9. public string firstName { get; set; }
  10. public string lastName { get; set; }
  11. }
Then we will look at the WebApiConfig.cs file in the App_Start folder.
  1. public static void Register(HttpConfiguration config)
  2. {
  3. config.Routes.MapHttpRoute(
  4. name: "DefaultApi",
  5. routeTemplate: "api/{controller}/{action}/{id}",
  6. defaults: new { id = RouteParameter.Optional }
  7. );
  8. }
So we can write the GET and POST methods as shown below.
  1. <!DOCTYPE>
  2. <html>
  3. <head>
  4. <title></title>
  5. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  6. <script language="javascript" type="text/javascript">
  7. /**********************************Request****************************************/
  8. var reqdata = {
  9. EmployeeName: "JD Mishra",
  10. empdetails: {
  11. email: '[email protected]',
  12. firstName: 'Jagdev',
  13. lastName: 'Mishra'
  14. }
  15. }
  16. var stringReqdata = JSON.stringify(reqdata);
  17. /*************************************GET*****************************************/
  18. function GetEmployeeInformation() {
  19. var url = "http://localhost:5000/api/Home/GetEmployeeInformation?JSONString=" + stringReqdata;
  20. jQuery.ajax({
  21. crossDomain: true,
  22. dataType: "json",
  23. url: url,
  24. async: false,
  25. context: document.body
  26. }).success(function (data) {
  27. alert(data);
  28. });
  29. };
  30. /*************************************GET*****************************************/
  31. function PostSubmitdata() {
  32. var url = "http://localhost:5000/api/Home/PostSubmitdata";
  33. jQuery.ajax({
  34. crossDomain: true,
  35. async: false,
  36. type: "POST",
  37. url: url,
  38. data: stringReqdata,
  39. dataType: "json",
  40. context: document.body,
  41. contentType: 'application/json; charset=utf-8'
  42. }).success(function (data) {
  43. alert(data);
  44. })
  45. }
  46. </script>
  47. </head>
  48. <body>
  49. <a href="#" onclick="GetEmployeeInformation();">Get</a><br />
  50. <a href="#" onclick="PostSubmitdata();">Post</a>
  51. </body>
  52. </html>
Thanks.