Skip to content

Instantly share code, notes, and snippets.

@ravindUwU
Last active May 26, 2025 11:24
Show Gist options
  • Save ravindUwU/ba7e7eb735a489dc8a44ee1f64528546 to your computer and use it in GitHub Desktop.
Save ravindUwU/ba7e7eb735a489dc8a44ee1f64528546 to your computer and use it in GitHub Desktop.
public static void UseCorsForPaths(
this IApplicationBuilder builder,
string policyName,
PathString[] paths
)
{
builder.Use(async (ctx, next) =>
{
if (paths.Any((p) => ctx.Request.Path.StartsWithSegments(p)))
{
var corsOptions = ctx.RequestServices.GetRequiredService<IOptions<CorsOptions>>();
var policy = corsOptions.Value.GetPolicy(policyName)
?? throw new InvalidOperationException($"CORS policy '{policyName}' not found.");
var corsService = ctx.RequestServices.GetRequiredService<ICorsService>();
var corsResult = corsService.EvaluatePolicy(ctx, policy);
if (corsResult.IsPreflightRequest)
{
corsService.ApplyResult(corsResult, ctx.Response);
ctx.Response.StatusCode = StatusCodes.Status204NoContent;
}
else
{
ctx.Response.OnStarting(() =>
{
try
{
corsService.ApplyResult(corsResult, ctx.Response);
}
catch { /* Ignored */ }
return Task.CompletedTask;
});
await next(ctx);
}
}
else
{
await next(ctx);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment