Skip to content

Instantly share code, notes, and snippets.

@nicocrm
Forked from mmorton/CrossOriginSupportModule.cs
Last active April 20, 2017 12:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicocrm/f19caf9655fa1745297cf5529c4b99be to your computer and use it in GitHub Desktop.
Save nicocrm/f19caf9655fa1745297cf5529c4b99be to your computer and use it in GitHub Desktop.
An IHttpModule for Enabling CORS
using System;
using System.Web;
namespace SSSWorld.CorsHelper
{
public class CrossOriginSupportModule : IHttpModule
{
public const string Options = "OPTIONS";
public const string Origin = "Origin";
public const string AccessControlRequestMethod = "Access-Control-Request-Method";
public const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
public const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
public const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
public const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
public const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
public const string AccessControlMaxAage = "Access-Control-Max-Age";
public void Init(HttpApplication context)
{
context.BeginRequest += ContextOnBeginRequest;
context.PreSendRequestHeaders += ContextOnPreSendRequestHeaders;
}
private void ContextOnPreSendRequestHeaders(object sender, EventArgs eventArgs)
{
var application = (HttpApplication)sender;
var context = application.Context;
var response = context.Response;
response.Headers[AccessControlAllowOrigin] = "*";
}
private void ContextOnBeginRequest(object sender, EventArgs eventArgs)
{
var application = (HttpApplication)sender;
var context = application.Context;
var request = context.Request;
if (!String.IsNullOrEmpty(request.Headers[Origin]))
{
if (request.HttpMethod == Options)
{
context.Response.Headers[CrossOriginSupportModule.AccessControlAllowMethods] = "GET,POST,PUT,OPTIONS,DELETE";
context.Response.Headers[CrossOriginSupportModule.AccessControlAllowHeaders] = "X-Requested-With, Authorization, X-Authorization, X-Authorization-Mode, User-Agent, Accept, Content-Type, If-Match, Cookie, X-Applicaton-Name, X-Application-Version";
context.Response.Headers[CrossOriginSupportModule.AccessControlMaxAage] = 1728000.ToString();
// interrupt request, so it does not get processed by SLX Authentication module
context.Response.End();
}
}
}
public void Dispose()
{
}
}
}
This module enables Cross Origin requests.
To use it, copy to the bin folder and add the following to web.config (make sure the add tag is at the top of the section):
<modules>
<add name="CrossOriginSupportModule" type="SSSWorld.CorsHelper.CrossOriginSupportModule, SSSWorld.CorsHelper" />
</modules>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment