.Net Core CORS 因自定义中间件而失败

.Net Cor CORS failing with custom middleware

我似乎无法让 CORS 与我在 .net core 3.1 web 中添加的一些自定义中间件一起工作 api。

我发现问题出在我实现的中间件上,如果我注释掉中间件行,它就可以工作,但是当我把它们放进去时却失败了:

app.UseMiddleware<ApiKeyMiddleware>(); // All request will need an ApiKey
app.UseMiddleware<UserTokenMiddleware>(); // All request but the /login and /swagger urls will need a UserToken

我需要做什么才能让它正常工作?

我的代码在Startup.cs文件中如下

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {   
        services.AddDbContext<ReminderContext>(options =>
        {
            options.UseSqlServer(this.Configuration.GetConnectionString("Reminder"));
        });

        services.AddCors();

        services.AddControllers().AddJsonOptions(opt =>
        {
            // Added this to support enum strings coming into the api, without it they won't work
            opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });

        services.AddSwaggerGen();

        services.AddMediatR(typeof(Startup), typeof(LoginHandler));

        // Using AddScoped means that the instance will be the same object for the whole request
        // This is good and means the unit of work will exist for the full requests wherever it is used

        // Unit of work
        services.AddScoped<IUnitOfWork, UnitOfWork>();

        // Add Repositories here
        services.AddScoped<IUserRepository, UserRepository>();

        // Add Business here
        services.AddScoped<ILoginBusiness, LoginBusiness>();
        services.AddScoped<IUserBusiness, UserBusiness>();
        services.AddScoped<IBirthdayBusiness, BirthdayBusiness>();

        services.AddSingleton<IPasswordUtility, PasswordUtility>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Middleware to intercept requests and check the ApiKey and UserToken
        app.UseMiddleware<ApiKeyMiddleware>(); // All request will need an ApiKey
        app.UseMiddleware<UserTokenMiddleware>(); // All request but the /login and /swagger urls will need a UserTokena

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            //c.RoutePrefix = string.Empty;
        });

        app.UseHttpsRedirection();

        app.UseRouting();

        //var corsUrls = Configuration.GetSection("Cors").Get<string[]>();
        app.UseCors(builder =>
        {
            builder.WithOrigins("http://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
        });

        //app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }
}

ApiKeyMiddleware 如下所示:

public class ApiKeyMiddleware
    {
        private readonly RequestDelegate _next;

        public ApiKeyMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, IConfiguration configuration)
        {
            // Check headers that a header had been passed and it is value
            if (!context.Request.Headers.Keys.Contains("ApiKey") ||
                context.Request.Headers["ApiKey"] != configuration["Security:ApiKey"])                
            {
                context.Response.StatusCode = 400; //Bad Request                
                await context.Response.WriteAsync("Invalid request");
                return;
            }
            await _next.Invoke(context); // call next middleware
        }
    }

我将中间件行移到 app.UseCors(...) 行下方,现在它似乎可以工作了!

app.UseMiddleware<ApiKeyMiddleware>(); // All request will need an ApiKey
app.UseMiddleware<UserTokenMiddleware>(); // All request but the /login and /swagger urls will need a UserToken

我现在可以真正进入swagger页面,而之前它也无法进入swagger页面。顺序似乎总是令人困惑。