How to enable cross origin requests in ASP.NET MVC 4 on POST using Angular 2
I found how to make it work. First I apply what proposed me sideshowbarker
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase) && Request.HttpMethod == "OPTIONS") { Response.Flush(); }
and I was missing something in my Headers, I was doing "*" all the way but finally with these parameters it worked
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
for those who are interested in the final form of my class here it is
using System;
using System.Web;
using System.Web.Mvc;
namespace Via.Client.WebMvc
{
public class AllowCrossSiteAttribute : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
filterContext.HttpContext.Response.Flush();
}
base.OnActionExecuting(filterContext);
}
}
}
Your frontend JavaScript code is triggering your browser to do a CORS preflight OPTIONS
request.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
You need to change the server-side code to handle that OPTIONS
request, by adding, for example:
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase) &&
Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
Or see https://stackoverflow.com/search?q=%5Basp.net-mvc%5D+%5Bcors%5D+options for many other related answers.