.Net Core CORS 因自定义中间件而失败 [重复]
Posted
技术标签:
【中文标题】.Net Core CORS 因自定义中间件而失败 [重复]【英文标题】:.Net Cor CORS failing with custom middleware [duplicate] 【发布时间】:2021-10-31 06:50:21 【问题描述】:我似乎无法让 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
【问题讨论】:
问:我需要什么才能让它工作?答:请阅读:Enable Cross-Origin Requests (CORS) in ASP.NET Core。然后试试这个:***.com/a/44379971/421195 这能回答你的问题吗? How to enable CORS in ASP.net Core WebAPI 第一个链接是我正在经历的,它没有提到 UseMvc() 但后面的链接确实如此。当我添加 UseMvc() 时,它指出“使用端点路由时不支持” 【参考方案1】:我将中间件行移到了 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 页面。排序总是让人困惑。
【讨论】:
以上是关于.Net Core CORS 因自定义中间件而失败 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
Spring Security 和 Keycloak 因自定义身份验证提供程序而失败
本地 Javascript Fetch Post 请求失败,调用 ASP.NET Core 2.2 Web API。 CORS 已启用
从我的自定义中间件返回到角度时,asp .net core api cors 问题
使用 Nginx 的 https SSL 证书验证因自定义构建的 libcurl+openssl 而失败,但适用于系统 curl
net.core 和 angular4 应用程序的 Cors 问题 - 适用于 azurewebsites.net 域而不是自定义