内容目录
In a Startup class, add a static variable:
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
Configure global CORS in services:
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder => builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());
});
Place the CORS middleware:
app.UseHttpsRedirection();
app.UseDefaultFiles(Program.Defaultfileoptions);
app.UseStaticFiles();
app.UseRouting();
#if CORS
app.UseCors(MyAllowSpecificOrigins);
#endif
Once configured, specify which Controllers or Actions allow CORS.
To configure CORS globally, add the following in the middleware routing configuration:
.RequireCors(MyAllowSpecificOrigins)
Example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
// Add SignalR service
// endpoints.MapHub<MessageHubs>("/Message");
});
If you only want to enable CORS for a specific Controller or Action, add the attribute above the Controller or Action:
[EnableCors]
文章评论