Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling Cross Domain ASP.net Web API

Tags:

I have Microsoft Visual Studio Express 2013 for Web, Version 12.0.30501.00 Update 2. I have a solution with 2 project in it, one is a web api, and the second is an MVC project intended for for the views. I have create a simple web api returning httpresponsemessage and I can go in fiddler and I will see the json response. However in my second project when attempting to call through ajax I received a cross domain error.

The solution I try to follow is this http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api. However when installing Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService in the console manager I received an error so I used this line instead. Install-Package Microsoft.AspNet.WebApi.Cors then I try to the next step which is config.EnableCors(); its state that

'System.Web.Http.HttpConfiguration' does not contain a definition for 'EnableCors' and no extension method 'EnableCors' accepting a first argument of type 'System.Web.Http.HttpConfiguration' could be found (are you missing a using directive or an assembly reference?) 

I am not sure what to afterward, I also try to add using System.Web.Http.Cors; but state that the namespace does not exists. This visual studio was downloaded about 3 weeks ago, I feel this feature should not be hard to install as it fully supported, is there something that i am missing?

like image 979
Jseb Avatar asked May 19 '14 19:05

Jseb


People also ask

How do I enable CORS in C#?

In order to enable CORS, we need to install the JSONP package from NuGet (see Figure3). After adding Jsonp package, we need to add the following code-snippet in App_Start\WebApiConfig. cs file. It creates instance of JsonpMediaTypeFormatter class and adds to config formatters object.

What is CORS in asp net Web API?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.

Is ASP Net Web API is cross platform?

ASP.NET is an open source web framework, created by Microsoft, for building modern web apps and services with . NET. ASP.NET is cross platform and runs on Linux, Windows, macOS, and Docker.


2 Answers

You should install a Nuget package Microsoft.AspNet.WebApi.Cors

From the menu in visual studio, go to Management Packages, and then type in the name of the package

Note:
To install from Package Manager Console, use Install-Package Microsoft.AspNet.WebApi.Cors

like image 195
Toan Nguyen Avatar answered Sep 19 '22 22:09

Toan Nguyen


install a Nuget package `"Microsoft.AspNet.WebApi.Cors" (version="5.1.0")

Add following line in your WebApiConfig.cs file

config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 
like image 25
Chandrika Prajapati Avatar answered Sep 21 '22 22:09

Chandrika Prajapati