net core 3.1 cross-domain Cors not find "Access-Control-Allow-Origin"

Original: NET 3.1 Core cross-domain Cors not find "Access-Control-Allow-Origin "

First, add ConfigureServices

Copy the code
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    // builder.AllowAnyOrigin () // allow host access from any source 
                    builder
                    
                    .WithOrigins ( " HTTP: //*.*.*.* " ) // .SetIsOriginAllowedToAllowWildcardSubdomains () // set the domain allowed access

                    .AllowAnyMethod()

                    .AllowAnyHeader()

                    .AllowCredentials();//

                });

            });
            services.AddControllers();
        }
Copy the code

Then add 

Copy the code
public class CorsMiddleware
    {
        private readonly RequestDelegate _next;
        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            await _next(context);
        }
    }
Copy the code

Then use the middleware

 app.UseMiddleware<CorsMiddleware>();

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12070762.html