Skip to content

Instantly share code, notes, and snippets.

@Kashkovsky
Last active November 6, 2020 10:33
Show Gist options
  • Save Kashkovsky/c07f87eced61a774bf1b74b9c9cb1c3c to your computer and use it in GitHub Desktop.
Save Kashkovsky/c07f87eced61a774bf1b74b9c9cb1c3c to your computer and use it in GitHub Desktop.
CORS delegating handler for Web API
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
//Add to Global.asax -- GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
namespace Common.Helpers
{
public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
var origin = request.Headers.GetValues(Origin).First();
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, origin);
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
t.Result.Headers.Add(AccessControlAllowOrigin, origin);
return t.Result;
}, cancellationToken);
}
return base.SendAsync(request, cancellationToken);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment