In this blog, we are going to learn, how we can learn cross origin request in ASP.NET Web API 2. We realize that ASP.NET Web API is independent. As of late, I ran into a requirement for calling our Web API in mobile Applications. Here, I am going to show you a basic example, where one is ASP.NET Web Application.
Background
(Cross-origin resource Sharing) is a World Wide Web Consortium. Essentially, it is considered as some portion of HTML5. Mobile application will call XML Http Request for Http verb (GET, POST, PUT, Delete, and so forth) to the ASP.NET Web Application, utilizing API. Naturally, the cross inception request is debilitated in ASP.NET Web API. When we have to call ASP.NET Web API, it should be empowered. We will concentrate more on our ASP.NET Web API, Mobile Application.
CORS is a concept that will be used like permissions to make cross-domain ajax requests. Let's understand the exact problem without cross enabling in WebApi 2.
You will find this error if WebApi 2 isn't already cross enabled.
Reasons why this type of error will occur:
- Your request differs in schemes (in other words http or https).
- You used different types of port numbers.
- Application has different domains or sub-domains types.
Now I have learned a lot of things about cross origin. Now for the solution of how to resolve it in webApi 2. Use this code to enable Cross origin.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web.Http;
- using Microsoft.Owin.Security.OAuth; W
- using Newtonsoft.Json.Serialization;
- using System.Web.Http.ExceptionHandling;
- using Crx.Utility;
- using System.Web.Http.Cors;
- using Microsoft.Practices.Unity;
- using Crx.Provider.Dictionaries;
- using CrxApi.ExLogger;
-
- namespace CrxApi
- {
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
-
-
-
-
- var corsAttr = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(corsAttr);
-
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
You can see in this code i have used 3 * Let me explain.
- 1st * is allowed to support any type Domain.
- 2nd * is allowed to support any type of header.
- 3rd * is allowed to support any type of content type.
Instead you can use hard code value.