【问题标题】:AWS Elastic beanstalk: ASP.NET Cors configuration not allowing hostsAWS Elastic beanstalk:ASP.NET Cors 配置不允许主机
【发布时间】:2022-01-17 23:13:24
【问题描述】:

我正在尝试获取一个 API 以允许来自源的请求。到目前为止,什么都没有通过,所以现在允许任何来源是目标,一旦它工作,我可以收紧访问。

API 用 ASP.net 编写并部署到弹性 beanstalk。当我尝试使用任何前端访问 API 时,我收到以下错误:

从源“http://localhost:{PORT_NUM}”访问“https://api.website.com/endpoint”处的 XMLHttpRequest 已被 CORS 策略阻止:否“Access-Control-Allow-Origin”请求的资源上存在标头。

Startup.cs 中的 Cors 配置:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddCors();

    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors(x => x
        .AllowAnyMethod()
        .AllowAnyHeader()
        .SetIsOriginAllowed(origin => true));

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

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

端点并没有以任何特殊方式进行图形化:

[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> Create([FromBody]CreateRequest request)
{
    //...
}

我有什么遗漏的吗?

我已阅读文档here 并尝试了此comment 中的代码。

【问题讨论】:

  • 可能发生的情况是,在管道到达 CORS 中间件之前,您的管道中有另一个错误 - CORS 错误可能掩盖了其他内容。只是一个理论。

标签: c# amazon-web-services asp.net-core cors amazon-elastic-beanstalk


【解决方案1】:

您可能需要设置 API 端点以返回 CORS 标头。修改Create,返回如下头:

// add CORS headers
{"Access-Control-Allow-Headers", "Content-Type"},
{"Access-Control-Allow-Origin", "*"},
{"Access-Control-Allow-Methods", "OPTIONS,POST,GET"}

如果您使用的是 AWS API Gateway,您还需要配置 DefaultCorsPreflightOptions。我是通过 CDK 完成的,但它看起来像这样:

DefaultCorsPreflightOptions = new CorsOptions
{
   AllowHeaders = new []{ "Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key" },
   AllowMethods = new []{ "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE" },
   AllowCredentials =  true,
   AllowOrigins = new []{ "*" }
}

我的演示仓库中的这些提交可能会有所帮助:https://github.com/ppittle/cdk-talk-2021/commit/19ded54e689c15cf5a23d9f461b97c0519decca5#diff-b30e8e7c0dda60b0346a05a7243f8ccb93397e7321e4ece9156798c5d1441131

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 2021-08-22
    • 2023-03-17
    • 2017-04-09
    • 2019-08-01
    • 2020-05-15
    • 2019-06-02
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多