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?
You can enable Cors in your web api project, by taking following steps:
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.
}?
[EnableCORS]
" attribute above Web-API Controller or Method, for exampleusing 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
}
}?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//enable cors globally
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
}
}?
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly