Last active
May 28, 2017 07:38
-
-
Save ThatRendle/6579306 to your computer and use it in GitHub Desktop.
Very basic CORS HttpModule
This file contains hidden or 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.Web; | |
namespace MyOtherSite | |
{ | |
public class CorsModule : IHttpModule | |
{ | |
public void Init(HttpApplication application) | |
{ | |
application.BeginRequest += ApplicationOnBeginRequest; | |
} | |
private void ApplicationOnBeginRequest(object sender, EventArgs eventArgs) | |
{ | |
var application = (HttpApplication) sender; | |
if (!CheckCors(application.Context)) | |
{ | |
application.Context.Response.StatusCode = 403; | |
application.CompleteRequest(); | |
} | |
} | |
private static bool CheckCors(HttpContext context) | |
{ | |
var origin = context.Request.Headers["Origin"]; | |
if (origin != "https://mysite.com") | |
{ | |
return false; | |
} | |
context.Response.AddHeader("Access-Control-Allow-Origin", origin); | |
context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); | |
context.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE"); | |
return true; | |
} | |
public void Dispose() | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myhost.com' is therefore not allowed access.
Code Snippet:
response.AddHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
response.AddHeader("Access-Control-Allow-Origin", origin);
response.AddHeader("Access-Control-Request-Methods", "POST,GET");
response.AddHeader("Access-Control-Allow-Credentials", "true");