enable CORS
done the following steps
Install the nuget package for CORS
: Install-Package Microsoft.AspNet.WebApi.Cors
.
Modify your WebApiConfig.cs
file with the Register
method by adding the following line
config.EnableCors();
You can enable CORS
in your controller in the following way
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORSWithWebAPI.Controllers
{
[EnableCors(origins: "http://client.domain", headers: "*", methods: "*")]
public class SampleController : ApiController
{
public HttpResponseMessage Post() { ... }
[DisableCors]
public HttpResponseMessage PutItem(int id) { ... }
}
}
You can enable CORS
at action level
public class SampleController : ApiController
{
[EnableCors(origins: "http://client.domain", headers: "*", methods: "*")]
public HttpResponseMessage GetSample(int id) { ... }
}
You can enable it globally by modifying point 1:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("client.domain", "*", "*");
config.EnableCors(cors);
}
}
Even from web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>