c# - ASP.NET Core AWS 无服务器和 CORS

标签 c# asp.net-core cors aws-serverless

我正在使用 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/

相关文章:

javascript - Strapi v4 抛出 cors 异常

javascript - CORS GET 在 Firefox 中返回一个空的响应主体

c# - 无效的 Double.ToString() 导致 Razor 代码生成 javascript

c# - 方法运行时 Richbox 不更新

c# - 存储库模式 : Add Item

asp.net-core - 如何在没有模型的 Razor 页面上使用 IPageFilter

firefox - 为什么我的 meteor 应用程序在 firefox 上出现这些错误,而在其他浏览器上却没有?

c# - 将 where 子句添加到嵌套的 Linq 选择

asp.net-core - 获取错误 : Entity type 'Course' is defined with a single key property,,但 2 个值已传递给 'DbSet.Find' 方法

asp.net-core - 动态加载 ASP.NET Core 程序集