public static IApplicationBuilder UseCrossOrigin(this IApplicationBuilder builder, string rootPath) { // // Allow CORs for rootPath only if (!string.IsNullOrEmpty(rootPath) || rootPath != "/") { builder.Use(async(context, next) => { bool isCorsPreflight = context.Request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase) && context.Request.Headers[HeaderNames.Origin].Any(); if (isCorsPreflight && !context.Request.Path.StartsWithSegments(rootPath)) { context.Response.StatusCode = (int)HttpStatusCode.NoContent; } else { await next.Invoke(); } }); } // // Setup var config = builder.ApplicationServices.GetRequiredService <IConfiguration>(); var corsConfiguration = new CorsConfiguration(config); builder.UseCors(cBuilder => { cBuilder.AllowAnyHeader(); cBuilder.WithExposedHeaders(HeaderNames.Total_Count, Net.Http.Headers.HeaderNames.Location, Net.Http.Headers.HeaderNames.Allow, Net.Http.Headers.HeaderNames.WWWAuthenticate); cBuilder.WithMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "DEBUG"); cBuilder.AllowCredentials(); IEnumerable <string> allowedOrigins = GetAllowedOrigins(corsConfiguration); if (allowedOrigins.Any(o => o.Equals("*"))) { cBuilder.AllowAnyOrigin(); } else { cBuilder.WithOrigins(allowedOrigins.ToArray()); } }); // We must allow OPTIONS to enter the application without integrated host authentication // We do not want OPTIONS methods to ever pass cors middleware builder.Use(async(context, next) => { if (!context.Request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase)) { await next.Invoke(); } }); return(builder); }
private static IEnumerable <string> GetAllowedOrigins(CorsConfiguration config) { return(config.Rules.Where(r => r.Allow).Select(r => r.Origin)); }