Skip to content

Instantly share code, notes, and snippets.

@robinbihun
Last active May 24, 2016 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinbihun/b9e4e03e8af7f80a3d6e472c1511c5af to your computer and use it in GitHub Desktop.
Save robinbihun/b9e4e03e8af7f80a3d6e472c1511c5af to your computer and use it in GitHub Desktop.
public class CorsHandler : DelegatingHandler
{
private const string _trustedRegex = @"((https?\:\/\/)?(.+\.)?thisismydomain\.com)|((https?\:\/\/)?localhost:[\d]+)";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// runs before controller
var response = base.SendAsync(request, cancellationToken);
// runs after controller
IEnumerable<string> origins;
request.Headers.TryGetValues("Origin", out origins);
var firstOrigin = origins?.FirstOrDefault();
if (firstOrigin != null && Regex.IsMatch(firstOrigin, _trustedRegex)) {
response.Result.Headers.Add("Access-Control-Allow-Origin", firstOrigin);
response.Result.Headers.Add("Access-Control-Allow-Headers", "*");
response.Result.Headers.Add("Access-Control-Allow-Credentials", "true");
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment