如何在ASP应用中禁用‘CORS policy execution successful’日志消息
禁用ASP.NET应用中「CORS policy execution successful」日志条目
可以通过调整日志过滤规则来屏蔽这类成功日志,具体有两种常用方式:
方式一:通过配置文件(appsettings.json)过滤
在appsettings.json的Logging节点下,针对Microsoft.AspNetCore.Cors命名空间设置更高的日志级别,比如将其设为Warning,这样Information级别的「CORS policy execution successful」就不会被记录:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore.Cors": "Warning" } } }
方式二:通过代码配置日志过滤
根据你的.NET版本,在启动配置中添加日志过滤规则:
.NET 6+ 顶级语句模式(Program.cs)
var builder = WebApplication.CreateBuilder(args); // 过滤CORS的Information级别日志 builder.Logging.AddFilter("Microsoft.AspNetCore.Cors", LogLevel.Warning); // 注册CORS服务及其他配置 builder.Services.AddCors(options => { // 你的CORS策略配置... }); var app = builder.Build(); // 启用CORS中间件 app.UseCors(); // 其他中间件配置... app.Run();
旧版本Startup.cs模式
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddLogging(loggingBuilder => { // 过滤CORS的Information级别日志 loggingBuilder.AddFilter("Microsoft.AspNetCore.Cors", LogLevel.Warning); }); services.AddCors(options => { // 你的CORS策略配置... }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 启用CORS中间件 app.UseCors(); // 其他中间件配置... } }
原理说明:「CORS policy execution successful」是CORS中间件输出的Information级别日志,通过将该命名空间的日志最低记录级别设为Warning,就会自动屏蔽所有Information及以下级别的日志,只保留警告、错误等更严重的日志条目。
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

