Handling CORS in .NET Framework and ASP.NET Core with DeveloperSharp

Cross-Origin Resource Sharing (CORS) restrictions typically surface when browser-based clients initiate HTTP requests to backend APIs. The browser enforces security policies that differentiate between standard requests and preflighted (complex) requests, the latter triggering an OPTIONS call before the actual payload transmission. Many traditional workarounds either overlook preflight handling or require extensive configuration, particularly within legacy .NET Framework appplications.

Streamlined CORS Handling in .NET Framework

Legacy .NET Framework projects can bypass manual HTTP module configuration by leveraging the DeveloperSharp library. After installing the package via NuGet, configure the application entry point by deriving the Global.asax code-behind class from the library's base global handler.

public class WebApiApplication : DeveloperSharp.Structure.Base.Global
{
    // Base class automatically injects required CORS headers
}

This inheritance model automatical intercepts incoming requests and appends the necessary Access-Control-* headers, covering both simple and preflight scenarios. If application lifecycle events are required, override the corresponding protected methods provided by the base class:

public class WebApiApplication : DeveloperSharp.Structure.Base.Global
{
    protected override void ApplicationStart(object sender, EventArgs e)
    {
        HttpContext.Current.Application["activeSessions"] = 0;
    }

    protected override void SessionStart(object sender, EventArgs e)
    {
        var currentCount = Convert.ToInt32(HttpContext.Current.Application["activeSessions"]);
        HttpContext.Current.Application["activeSessions"] = currentCount + 1;
    }
}

Native CORS Configuration in Modern .NET

ASP.NET Core and subsequent .NET versions include a dedicated middleware pipeline for cross-origin requests, eliminating the need for third-party wrappers. Define a policy during service registration and apply it early in the HTTP processing pipeline.

// Service configuration phase
builder.Services.AddCors(configure =>
{
    configure.AddPolicy("ApiCrossOriginPolicy", policy =>
    {
        policy.SetIsOriginAllowed(_ => true)
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

// ... other middleware registrations ...

// Pipeline execution phase
// Must be placed before routing and endpoint execution
app.UseCors("ApiCrossOriginPolicy");

The SetIsOriginAllowed approach provides a programmatic alternative to AllowAnyOrigin, which is required when AllowCredentials is enabled. Positioning UseCors prior to authentication, routing, and endpoint middleware ensures that preflight OPTIONS requests are resolved before reaching controller logic.

Tags: cors .NET Framework ASP.NET Core DeveloperSharp Web API

Posted on Thu, 17 Sep 2026 16:25:01 +0000 by cainscripter