Skip to content

Instantly share code, notes, and snippets.

@mattmazzola
Created September 25, 2015 07:01
Show Gist options
  • Save mattmazzola/a2e936fea6a2d589b06f to your computer and use it in GitHub Desktop.
Save mattmazzola/a2e936fea6a2d589b06f to your computer and use it in GitHub Desktop.
CORS Attribute that matches based on regular expression from Web.config
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Cors;
using System.Web.Http.Cors;
namespace CorsOriginRegexWebAPI.CORS
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class RegexCorsAttribute : Attribute, ICorsPolicyProvider
{
public async Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken token)
{
var corsRequestContext = request.GetCorsRequestContext();
var originRequested = corsRequestContext.Origin;
if (await IsOriginAcceptable(originRequested))
{
// Grant CORS request
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
};
policy.Origins.Add(originRequested);
return policy;
}
else
{
return null;
}
}
private async Task<Boolean> IsOriginAcceptable(string origin)
{
var pattern = ConfigurationManager.AppSettings["CorsRegexPattern"];
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(origin);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment