I want to use CORS with multiple sources for my web application but I am stuck now. It worked with the first source because I set the Allow-Origin header from Web.config. But now I want to do it programmatically to change the header based on the Origin/Referer.
- won't work in browsers like Chrome.
I created the Application_BeginRequest in Global.asax. Problem is...it is only triggered for GET/POST requests but not for the OPTIONS call.
Second option to add OnActionExecuting in a global filter. Same problem. OPTIONS requests don't trigger this method.
Any idea what is going around here?
I am using .NET Framework 4.8.
Code:
public class MyActionFilterAttribute : ActionFilterAttribute
{
private readonly string NEEDS_CUSTOM_ORIGIN = ConfigurationManager.ConnectionStrings["CustomOrigin"]?.ConnectionString ?? "";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
// IT NEVER HITS THIS OR ANY OTHER PART OF THIS METHOD FOR OPTIONS
}
if (!string.IsNullOrWhiteSpace(NEEDS_CUSTOM_ORIGIN))
{
var originHeader = "";
if (((IList)filterContext.HttpContext.Request.Headers.AllKeys).Contains("Origin"))
{
originHeader = filterContext.HttpContext.Request.Headers["Origin"];
}
else if (((IList)filterContext.HttpContext.Request.Headers.AllKeys).Contains("Referer"))
{
originHeader = filterContext.HttpContext.Request.Headers["Referer"];
}
if (!string.IsNullOrWhiteSpace(originHeader))
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", originHeader);
}
}
}
}
Global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(Request.HttpMethod == "OPTIONS")
{
// NEVER
}
}