Last active
May 26, 2025 11:24
-
-
Save ravindUwU/ba7e7eb735a489dc8a44ee1f64528546 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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