How do I enable CORS in C# web-api 2?


I have read and implemented "Token based authentication in C# using Web API" in my web-api project, now, I would like to enable CORS in my web-api so anyone can access api from different domain also. How can enable CORS in web-api?


Asked by:- bhanu
0
: 5202 At:- 8/20/2020 2:20:52 PM
C# Enable CORS in web-api







2 Answers
profileImage Answered by:- vikas_jk

You can enable Cors in your web api project, by taking following steps:

  1. "Install-Package Microsoft.AspNet.WebApi.Cors" from NuGet Package Manager console
  2. Once the above Package is installed, open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method
     public static void Register(HttpConfiguration config)
            {
                //add to enable cors
                config.EnableCors(cors);
               
    
                //old code, route config etc.
            }?
  3. Once done, you can add "[EnableCORS]" attribute above Web-API Controller or Method, for example
    using System.Web.Http.Cors; //add namespace
    
    namespace WebService.Controllers
    {
        [EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
        public class SampleController : ApiController
        {
            // your API Controller code here
        }
    }?
  4. You can enable CORS globally also, using the following code in your WebApiConfig.cs
     public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {    
               //enable cors globally
                var cors = new EnableCorsAttribute("www.example.com", "*", "*");
                config.EnableCors(cors);
            }
        }?

Source: Enabling CORS in IIS (Various possible methods)

1
At:- 8/20/2020 2:27:03 PM
Thanks for Quick answer, works as needed. 0
By : bhanu - at :- 8/20/2020 2:37:45 PM


profileImage Answered by:- bhanu

I have found one more way, which works fine, but it doesn't allow you do define CORS on controller basis.

You can use the below code in your web.config to enable CORS through out your application

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

One more disadvantage of this using approach is it causes the header to be included in every response from your api server.

0
At:- 8/20/2020 2:40:58 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use