Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to enable CORS (Cross-Origin Requests) in ASP.NET Web API

    • 0
    • 8
    • 4
    • 3
    • 0
    • 0
    • 0
    • 0
    • 4.07k
    Comment on it

    There are certain steps that need to be followed for enabling CORS in ASP.NET Web API :


    Step 1: We Have to install the CORS Package, and to install it , open Nuget Package Manager console and type and run command Install-Package Microsoft.AspNet.WebApi.Cors, this will install all the CORS packages.


    Step 2: Now in Global.asax file, we define Default Route for the Web API

    public class WebApiApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                RouteTable.Routes.MapHttpRoute(
                          name: "DefaultApi",
                          routeTemplate: "api/{controller}/{id}",
                          defaults: new { id = RouteParameter.Optional }
                      );
    
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
        }
    


    Step 3: Now to enable CORS , we have to add some line of code, just before the Default Route of API in Application_Start() function in Global.asax file

    var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
    GlobalConfiguration.Configuration.EnableCors(cors);
    

    Here EnableCorsAttribute takes 3 parameters, which are

    1. origins (Ex. "http://www.xyz.com")
    2. headers: "*"
    3. methods: "*"


    Step 4:Now we will define the Controller and Action Method of the Web API, which goes like this

    public class ValuesController : ApiController
        {
            public string Get(string fisrtName, string lastName)
            {
                return "FullName is : " + fisrtName + ' ' + lastName;
            }
        }
    


    Note: Here the controller 'ValuesController', must inherits from ApiController, which is already present in MVC, and it provides basic functionalities for making Http request.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: