Skip to content

Instantly share code, notes, and snippets.

@sadrakgunadi
Last active March 30, 2019 15:47
Show Gist options
  • Save sadrakgunadi/cf821a06a738463edcf86ba301a0d5c1 to your computer and use it in GitHub Desktop.
Save sadrakgunadi/cf821a06a738463edcf86ba301a0d5c1 to your computer and use it in GitHub Desktop.
Web API CORS Preflight issues
Web Config
-----------
<system.webServer>
<httpProtocol>
<!--<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>-->
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Global asax
-----------
protected void Application_BeginRequest(object sender, EventArgs e) {
if (Context.Request.HttpMethod.Equals("OPTIONS")) {
Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, POST");
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-DRIB-ENCRYPTED-DATA");
Response.AddHeader("Access-Control-Allow-Credentials", "true");
Response.AddHeader("Access-Control-Allow-Max-Age", "86400");
Response.End();
}
}
Handler
-------
protected override Task < HttpResponseMessage > SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
if (request.Method.Method.Equals("OPTIONS")) {
var Response = new HttpResponseMessage {
StatusCode = System.Net.HttpStatusCode.OK
};
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, PUT, POST");
Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-DRIB-ENCRYPTED-DATA");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Headers.Add("Access-Control-Allow-Max-Age", "86400");
var Tsc = new TaskCompletionSource < HttpResponseMessage > ();
Tsc.SetResult(Response);
return Tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment