我正在使用 Visual Studio 将 ASP.NET Core 2.1 应用程序发布到 AWS Lambda(无服务器)。无论我尝试过什么,我都无法让 CORS 工作。
我真正想做的就是添加标题 access-control-allow-origin
全局到我的网络应用程序。
有没有人成功地将 header 添加到 ASP.NET Core 2.1 无服务器应用程序?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// AddCors must be before AddMvc
services.AddCors();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// UseCors must be before UseMvc
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
// Also tried this
// app.UseCors(
// o => o.WithOrigins("http://example.com").AllowAnyMethod()
//);
app.UseMvc();
}
我的页面中没有添加 CORS header 。我正在使用 Chrome 开发工具来检查我的标题。我应该在主页上看到它们(例如)对吗?
有任何想法吗?我快死在这里了。谢谢!
编辑
此应用程序仅使用 API Gateway、Lambda 和一些其他服务。这很棒,因为我只在有人点击我的应用程序时收费。没有按小时收费。没有 EC2 或 ELB,这太棒了。
此外,我几乎将其添加到我的原始帖子中。 article @sturcotte06 引用有一个问题。
API 网关(自动生成)在代理集成中使用 ANY 方法。上面的文章是这样说的...
Important
When applying the above instructions to the ANY method in a proxy integration, any applicable CORS headers will not be set. Instead, your backend must return the applicable CORS headers, such as Access-Control-Allow-Origin.
啊!所以它说我必须在后端执行此操作(Startup.cs 对吗?)这正是发布时似乎被忽略的内容。
最佳答案
无论出于何种原因 app.UseCors 在我的场景中不起作用。但是, app.Use 确实...
app.Use((context, next) =>
{
context.Response.Headers["Access-Control-Allow-Origin"] = "https://example.com";
return next.Invoke();
});
app.UseMvc();
关于c# - ASP.NET Core AWS 无服务器和 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58980871/