我的 startup.cs Configure 方法中有一个工作异常处理程序,它在下面被注释掉并替换为中间件调用。一旦我集成了中间件,我的 CORS 就开始失败了。我尝试将它移动到堆栈中 Cors 调用的下方,但这没有任何区别。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseMiddleware<ExceptionMiddleware>();
/*
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var errorMessage = $"Error: {ex.Error.Message}";
if (!env.IsDevelopment())
{
_logger.LogError(errorMessage, ex);
}
await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
}
});
});
*/
app.UseRequestTracking();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc();
}
这里是异常处理程序的代码
public class ExceptionMiddleware : IMiddleware
{
private readonly ILogger _logger;
public ExceptionMiddleware(ILogger<ExceptionMiddleware> logger)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var errorMessage = $"Error: {ex.Error.Message}";
_logger.LogError(errorMessage, ex);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
}
else
{
await next(context);
}
}
}
我为你的框架版本检查了关于基于工厂的中间件的文档,并且还需要通过以下方式修改
ConfigureServices
方法:
public void ConfigureServices(IServiceCollection services)
{
// some configuration
services.AddTransient<ExceptionMiddleware>();
// another configuration
}
也许这是你的情况所缺少的东西。