Created
May 14, 2014 01:59
-
-
Save shaunxu/8414a78cd8074432fc69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CrossDomainHandler : 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; | |
if (isCorsRequest) | |
{ | |
if (isPreflightRequest) | |
{ | |
return Task.Factory.StartNew(() => | |
{ | |
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); | |
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); | |
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); | |
} | |
else | |
{ | |
return base.SendAsync(request, cancellationToken).ContinueWith(t => | |
{ | |
HttpResponseMessage resp = t.Result; | |
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); | |
return resp; | |
}); | |
} | |
} | |
else | |
{ | |
return base.SendAsync(request, cancellationToken); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Configuration(IAppBuilder app) | |
{ | |
var config = new HttpConfiguration(); | |
config.MessageHandlers.Add(new CrossDomainHandler()); | |
app.UseWebApi(config); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment