Created
March 4, 2019 05:39
-
-
Save seangwright/cbf27c9e98d4dd2e8586ee57c865ce01 to your computer and use it in GitHub Desktop.
ken120-mvc-vuejs-CorsModule.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
using System.Linq; | |
using System.Web; | |
namespace CMS.Cors | |
{ | |
public class CorsModule : IHttpModule | |
{ | |
private readonly string[] allowedOrigins; | |
public CorsModule() => | |
allowedOrigins = ConfigurationManager | |
.AppSettings["application:cors:allow-origin"] | |
.Split(','); | |
public void Init(HttpApplication context) => | |
context.BeginRequest += new EventHandler(Application_BeginRequest); | |
public void Application_BeginRequest(object o, EventArgs ea) | |
{ | |
var context = HttpContext.Current; | |
var referrerUri = context.Request.UrlReferrer; | |
if (referrerUri is null) | |
{ | |
return; | |
} | |
string referrerOrigin = referrerUri.GetLeftPart(UriPartial.Authority); | |
if (!allowedOrigins.Any(origin => string.Equals(origin, referrerOrigin, StringComparison.OrdinalIgnoreCase))) | |
{ | |
return; | |
} | |
context.Response.Headers.Add("Access-Control-Allow-Origin", referrerOrigin); | |
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); | |
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET"); | |
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type"); | |
} | |
public void Dispose() { } | |
} | |
} | |
/* How to use this module | |
Add the following to <system.webServer><modules> | |
<add name="CORSModule" preCondition="managedHandler" type="CMS.Cors.CorsModule, CMSApp"/> | |
Add the following to <system.webServer>handlers> | |
<remove name="ExtensionlessUrlHandler-Integrated-4.0" /> | |
<remove name="OPTIONSVerbHandler" /> | |
<remove name="TRACEVerbHandler" /> | |
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> | |
Add the following entry to your AppSettings - the list is comma delimited | |
<add key="application:cors:allow-origin" value="https://localhost:44397,https://localhost:44392,https://localhost:44391"/> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment