简体   繁体   English

CORS 停止 Angular 应用程序和 .NET CORE 3.0 ZDB974238714CA8DE634A7CE1D083A1 之间的通信

[英]CORS stopping communication between Angular app and .NET CORE 3.0 API

I tried to avoid posting this question as there are so many others like, but after trying what seems like every combination none have solved my issue.我试图避免发布这个问题,因为有很多其他人喜欢,但是在尝试了似乎每种组合之后,没有一个能解决我的问题。

The Problem问题

My angular application CAN POST to my web API when it's running locally on IIS EXPRESS.我的 angular 应用程序可以 POST 到我的 web API 当它在 Z5DA5EXF461B7EFB7E76ECPRESS11 上本地运行时。 But when the API is deployed to IIS my Angular app CANNOT POST to it.但是当 API 部署到 IIS 时,我的 Angular 应用程序无法发布到它。 However it can successfully perform a GET request in both environments.但是,它可以在两种环境中成功执行 GET 请求。

The Error错误

Access to XMLHttpRequest at 'https://mySite:1234/api/v1/postData' from origin 'https://mySite:1233' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“https://mySite:1233”访问“https://mySite:1234/api/v1/postData”处的 XMLHttpRequest 访问控制检查:否'Access-Control-Allow-Origin' header 存在于请求的资源上。

What I've tried/the code我尝试过的/代码

Both applications run on different ports so I understand why I need to configure CORS and after quite a bit of reading I found that a pre-flight request is not made for GET requests ( as covered in the Mozilla Docs ), so that would explain why the GET request succeeds.两个应用程序都在不同的端口上运行,所以我明白为什么我需要配置 CORS 并且经过大量阅读后,我发现没有为 GET 请求发出飞行前请求(如 Mozilla Docs 中所述),所以这可以解释为什么GET 请求成功。 The Mozilla docs lead me to believe that my POST does not come under the simple request category as it require authorisation, but that does not answer way it works on IIS EXPRESS and not on IIS (I assume express is a bit less strict?). Mozilla 文档让我相信我的 POST 不属于简单请求类别,因为它需要授权,但这并不能回答它在 IIS EXPRESS 而不是 IIS 上的工作方式(我认为 express 不那么严格?)。

After following the official docs and NOT being able to get it to work then looking at various SO posts and trying various options, I've come to a dead-end and really hope someone can point out where I've gone wrong在遵循官方文档并且无法使其正常工作然后查看各种SO 帖子并尝试各种选项之后,我走到了死胡同,真的希望有人能指出我哪里出错了

Startup.cs启动.cs

public class Startup
{
    private const string ALLOWED_ORIGINS = "allowedOrigin";
    ...other stuff...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: ALLOWED_ORIGINS,
                builder =>
                {
                    builder.WithOrigins("https://myLocalSite:1233", "https://myDeployedSite:1233")//these values are retrieve from config 
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                });
        });

        services.AddControllers()

        ....other stuff... 

        services.AddMvc(o =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            o.Filters.Add(new AuthorizeFilter(policy));
        });

        ....other stuff... 
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...other stuff...

        app.UseRouting();

        app.UseCors(ALLOWED_ORIGINS);

        app.UseAuthentication();

        app.UseAuthorization();

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

The controller controller

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class PostDataController : ControllerBase
{
    ...other stuff...

    [HttpPost]
    public async Task<SomeResponse> Post(SomeRequest sr)
    {
        ...other stuff...
    }
}

Finally最后

I have not added any angular code as I believe that the issue is in my API set up.我没有添加任何 angular 代码,因为我相信问题出在我的 API 设置中。 I will be happy to add the code if needed though如果需要,我很乐意添加代码

  1. Try putting AddMvc BEFORE "AddCors".尝试将 AddMvc 放在“AddCors”之前。

  2. Sanity checks: start with AllowAnyOrigin, and work your ways to more granular definition健全性检查:从 AllowAnyOrigin 开始,按照自己的方式进行更精细的定义

    public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddCors(); } public void Configure(IApplicationBuilder app) { app.UseCors(policy => policy.WithOrigins(ALLOWED_ORIGINS)); }

Looks like you have those (above).看起来你有那些(上图)。

Do you have (below)?你有(下)吗?

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<CorsOptions>(options =>
        {
            options.AddPolicy(
                "AllowAnySimpleRequest",
                builder =>
                {
                    builder.AllowAnyOrigin()
                           .WithMethods("GET", "POST", "HEAD");
                });

Check out this file for a better "full context" code.查看此文件以获得更好的“完整上下文”代码。 https://csharp.hotexamples.com/site/file?hash=0x8b07b2262d54348025f4b69ad1c3a6e517321a0d14cca0e0bf05aed12f88424f&fullName=Startup.cs&project=psilon2000/LUV https://csharp.hotexamples.com/site/file?hash=0x8b07b2262d54348025f4b69ad1c3a6e517321a0d14cca0e0bf05aed12f88424f&fullName000/VLU.cs&project=psilon2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM