I create a web service on Web API and try to use it from angular 2 application. I install Microsoft.AspNet.WebApi.Core 5.2.3 and configure it to allow cors. It hosted on local IIS at localhost/RestfulAPI
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi 2",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var cors = new EnableCorsAttribute("*", "*", "*"); // origins, headers, methods
config.EnableCors(cors);
}
}
controller
[HttpGet]
[Route("api/product/details")]
public async Task<IHttpActionResult> GetProductsDetails([FromUri]ProductSearch model)
{
using (var unitOfWork = Factory.Create())
{
var products = (from p in await unitOfWork.GetProductsAsync(model?.CategoryID, model?.BrandID, model?.ProductStateID, null, model?.PartnerID,
true, model?.Code)
orderby p.Code
select p).ToArray();
return return Json(products);
}
}
But I'm still get error in browser.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:12012' is therefore not allowed access. The response had HTTP status code 404.
How could it be, that I enabled all cors, but it still not working?
Upd.1. I try to handle an options request like bellow
public class PreflightRequestsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
// Define and add values to variables: origins, headers, methods (can be global)
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "*");
response.Headers.Add("Access-Control-Allow-Methods", "*");
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
But get an error: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.