<p>When integrating a frontend application hosted on a separate origin with an ASP.NET WebAPI backend, Cross-Origin Resource Sharing (CORS) policies often block requests. This is particularly common when the client requires authentication credentials. The browser enforces specific security checks during the preflight process, and failure to configure the server correctly results in connection errors.</p> <h3>Restricting Allowed Origins with Credentials</h3> <p>If the client-side request sets <code>withCredentials</code> to true, the server cannot respond with a wildcard (<code>*</code>) for the <code>Access-Control-Allow-Origin</code> header. Browsers will block the response if the origin is not explicitly specified. To resolve this, define the specific frontend URL in the IIS configuration.</p> <pre><code><system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost:9528" /> </customHeaders> </httpProtocol> </system.webServer></code></pre> <h3>Enabling Credential Support</h3> <p>Another common failure occurs when the server does not explicitly allow credentials. The browser expects the <code>Access-Control-Allow-Credentials</code> header to be set to <code>true</code> when the request mode includes credentials. Add the following header configuration to <code>web.config</code>:</p> <pre><code><add name="Access-Control-Allow-Credentials" value="true" /></code></pre> <h3>Handling OPTIONS Preflight Requests</h3> <p>Browsers send an OPTIONS request before the actual HTTP verb to verify CORS permissions. If the server does not handle this method, IIS may return a 405 Method Not Allowed status, causing the preflight check to fail. To fix this, implement a custom HTTP module that intercepts OPTIONS requests and returns a 200 OK status immediately.</p> <pre><code>public class CorsPreflightModule : IHttpModule { public void Init(HttpApplication application) { application.BeginRequest += OnPipelineStart; } public void Dispose() { // Cleanup resources if necessary } private void OnPipelineStart(object sender, EventArgs e) { var app = sender as HttpApplication; if (app != null && IsPreflightRequest(app.Request)) { app.Response.StatusCode = 200; app.Response.StatusDescription = "OK"; app.CompleteRequest(); } } private bool IsPreflightRequest(HttpRequest request) { return string.Equals(request.HttpMethod, "OPTIONS", StringComparison.OrdinalIgnoreCase); } }</code></pre> <p>After compiling the module, register it within the <code>system.webServer</code> section of the configuration file. The registration name must match the class implementation deployed to the bin folder.</p> <pre><code><configuration> <system.webServer> <modules> <add name="CorsPreflightModule" type="CorsPreflightModule" /> </modules> </system.webServer> </configuration></code></pre>
Handling CORS Preflight and Credentials in ASP.NET WebAPI
Posted on Mon, 11 May 2026 05:38:34 +0000 by filn