【问题标题】:Access-Control-Allow-Origin Problem in .NET Core Deployed at IIS Configured on Windows Server 2016在 Windows Server 2016 上配置的 IIS 上部署的 .NET Core 中的 Access-Control-Allow-Origin 问题
【发布时间】:2020-06-06 11:49:24
【问题描述】:

我在这里查看了Enable Cross-Origin RequestsSO Answers 的几个文档,但我仍然没有做对。还关注Installed IIS CORS module

我有一个在 AWS EC2 Windows Server 2016 数据中心的 IIS 上运行的 .net core api 3.1,其端点类似于 https://6.13.21.111/api/user/authenticate。我有一个 Angular 8 前端应用程序在 AWS Amplify url 上运行,例如 https://tests.d1nkxxfifp945dd.myapp.com 每当我向 API 发出请求时,都会出现以下错误。

从源“https://tests.d1nkxxfifp945dd.myapp.com”访问“https://6.13.21.111/api/user/authenticate”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。 zone.js:3372 POST https://6.13.21.111/api/users/authenticate net::ERR_FAILED

当我从http://localhost:4200/ 向端点发送请求时也遇到了同样的问题 我已经设置了以下

Startup.cs

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

    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder.AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
        });

        services.AddControllers();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors(MyAllowSpecificOrigins);
        app.UseAuthentication();

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

用户控制器

[Route("api/[controller]")]
[EnableCors("MyAllowSpecificOrigins")]
[ApiController]
public class UsersController : ControllerBase
{

    private IUserService _userService;

    public UsersController(IUserService userService)
    {
        _userService = userService;

    }

    [HttpPost("authenticate")]
    public Task<ApiResponse> Authenticate([FromBody]UserRequest userRequest)
    {
        return _userService.Authenticate(userRequest);
    }

}

【问题讨论】:

    标签: c# .net angularjs asp.net-core


    【解决方案1】:

    尝试将“AllowAnyOrigin”更改为 withOrigin("your amazon angular url") 看看是否能解决问题。

    【讨论】:

    • 我希望他们还必须通过在构建器对象上调用 AllowCredentials 来指定应允许的凭据。
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 2014-06-07
    • 2017-08-12
    • 2016-04-22
    • 1970-01-01
    • 2017-10-20
    • 2023-02-14
    • 2017-06-21
    相关资源
    最近更新 更多