According to asp.net tutorial, we only need following code to enable cors on Web Api
application:
var cors = new EnableCorsAttribute("*","*", "*");
config.EnableCors(cors);
Following is my code:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*","*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
It is working fine for Get
, but still it is giving error for Post
requests
Following is the error, I am getting on Post:
POST http://api.example.com/token 404 (Not Found) XMLHttpRequest cannot load http://api.example.com/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access. The response had HTTP status code 404.