No 'Access-Control-Allow-Origin' header in asp core and angular7

前端 未结 2 543
情歌与酒
情歌与酒 2020-12-11 13:07

i need to download image from backend Asp Core 2.2 and show it in Angular .

i create a component for show image in angular :

in Html Code :

&         


        
相关标签:
2条回答
  • 2020-12-11 13:43

    ASP.NET Core 2.2 doesn't allow the combination of AllowAnyOrigin and AllowCredentials. You need to change AllowAnyOrigin to SetIsOriginAllowed:

    app.UseCors(builder => builder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .SetIsOriginAllowed((host) => true)
                    .AllowCredentials()
                );
    
    0 讨论(0)
  • 2020-12-11 14:07

    While the other answer is correct, if you however want to define specific allowed origins (and you should), you should remove .AllowAnyOrigin() or SetIsOriginAllowed((host) => true) from your CORS statement and it will work with .AllowCredentials().

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .WithOrigins("http://localhost:4200")
                      .AllowCredentials()
                .Build());
    
            });
    

    And if you want to allow multiple Origins, you can set an array of origins and use that as the param in .WithOrigins(). E.g:

    private readonly string[] MyAllowedOrigins = new string[] {
        "http://localhost:4200",
        "http://localhost:3000"
    };
    
    ...
    .WithOrigins(MyAllowedOrigins)
    ...
    

    Also, pay attention to the scheme used - check if it's http or https.

    For the sake of completeness, never forget to add e.g. app.UseCors("CorsPolicy"); where you configure your pipeline, e.g. .Configure method in the Startup class.


    All in all - while in some cases allowing any origin could be okay, you usually want and should define the allowed origins specifically.

    Regarding SetIsOriginAllowed((host) => true) - this should be an expression to evaluate whether an origin should be allowed, making it return => true always, could be fine under a dev. environment, but shouldn't be used in production as far as I can tell.

    You can find a good read on MS Docs. Checkout:

    • Enable Cross-Origin Requests
    • CorsPolicyBuilder
    • AllowAnyOrigin
    • WithOrigins
    • SetIsOriginAllowed
    0 讨论(0)
提交回复
热议问题