Search code examples
.net-coremiddleware

.NET Core 3.1 adding middleware broke CORS


I had a working exception handler in my startup.cs Configure method which is commented out below and replaced with the middleware call. Once I integrated the middleware instead my CORS began failing. I tried moving it to below the Cors call in the stack but that made no difference.

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();

}

Here is the code for the exception handler

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);
        }
    }
}

Solution

  • I checked documentation about the factory-based middleware for your framework version, and there is a need to also modify the ConfigureServices method by:

    public void ConfigureServices(IServiceCollection services)
    {
        // some configuration
    
        services.AddTransient<ExceptionMiddleware>();
    
        // another configuration
    }
    

    Maybe it is something that is missing in your case.