Skip to content

Instantly share code, notes, and snippets.

@markrendle
Last active May 28, 2017 07:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrendle/6579306 to your computer and use it in GitHub Desktop.
Save markrendle/6579306 to your computer and use it in GitHub Desktop.
Very basic CORS HttpModule
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()
{
}
}
}
@ManasPandey
Copy link

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");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment