Skip to content

Instantly share code, notes, and snippets.

@GeoffCox
Created April 16, 2015 00:07
Show Gist options
  • Save GeoffCox/0f04e4044ded5f156829 to your computer and use it in GitHub Desktop.
Save GeoffCox/0f04e4044ded5f156829 to your computer and use it in GitHub Desktop.
Allow multiple origins for CORS using ASP.NET MVC
protected void Application_BeginRequest()
{
this.SetupCorsHeaders();
//OPTIONS request comes before the POST to know the permissions. this forces to send the reply.
if (((IList)Request.Headers.AllKeys).Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
private void SetupCorsHeaders()
{
const string IncomingOriginHeader = "Origin";
const string OutgoingOriginHeader = "Access-Control-Allow-Origin";
const string OutgoingMethodsHeader = "Access-Control-Allow-Methods";
const string OutgoingHeadersHeader = "Access-Control-Allow-Headers";
const string OutgoingAgeHeader = "Access-Control-Max-Age";
var isLocal = Request.IsLocal;
var originHeader = Request.Headers.Get(IncomingOriginHeader);
if (!String.IsNullOrWhiteSpace(originHeader) && (isLocal || IsAllowedOrigin(originHeader)))
{
Response.AddHeader(OutgoingOriginHeader, originHeader);
Response.AddHeader(OutgoingMethodsHeader, "POST,OPTIONS");
Response.AddHeader(OutgoingHeadersHeader, "Content-Type");
Response.AddHeader(OutgoingAgeHeader, "3600");
}
}
private bool IsAllowedOrigin(string origin)
{
//TODO: determine what origins are allowed
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment