How to activate cors in a asp.net website (razor 3)

252 Views Asked by At

I am pretty new to ASP.NET Website programming. I have an node js express application where I need to make requests to. This currently doesnt works from my asp.net site because i dont have cors enabled. I hope you can help me and if I am just beeing stupid and configured my website wrong or forgot to add a controller please let me know.

I tried adding cors package via nuget and adding it to the web.config.

1

There are 1 best solutions below

2
awais On

In the Solution Explorer, expand the WebApi project. Open the file App_Start/WebApiConfig.cs, and add the following code to the method WebApiConfig.Register.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Then add the attribute [EnableCors] to the desired controller:

namespace MyProject.Controllers
{
    [EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}