When
The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported
Just give a trusted list. The amendment is as follows:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder.WithOrigins(new string[] { "http://127.0.0.1:5500" }) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }));
If you really don't want to make any restrictions, there are ways. Just replace AllowAnyOrigin with setisoriginallowed (_ =>True).
services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder.AllowAnyMethod() .SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowCredentials(); }));
In addition to the previous two methods, you can also customize the middleware. Add a Cors processing class. As follows:
public class CorsMiddleware { private readonly RequestDelegate next; public CorsMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { if (context.Request.Headers.ContainsKey(CorsConstants.Origin)) { context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]); context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH"); context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]); context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); if (context.Request.Method.Equals("OPTIONS")) { context.Response.StatusCode = StatusCodes.Status200OK; return; } } await next(context); } }
Add the following to the Configure method.
app.UseMiddleware<CorsMiddleware>();