【问题标题】:.NET CORE 2.0 Angular 5: Allowing Cors.NET CORE 2.0 Angular 5:允许 Cors
【发布时间】:2018-07-05 15:10:26
【问题描述】:

我在允许 cors 时遇到了一些问题。我已经这样设置server side

  app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader());

startup 类的configure 方法内部

当我的网络 API 被点击时,它会很好地返回数据。

但是,问题似乎出在 Angular 上,因为我收到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

这是我的 Angular Web api 调用

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';;


@Injectable()
export class ProfileService {

    private baseUrl = 'api/profile/';

    constructor(private http: HttpClient) { }

    getLookups(step: number) {
        return this.http.get('http://localhost:51658/' + this.baseUrl + 'lookups/' + step)
    }

}

【问题讨论】:

  • 您的 ASP.NET Core 应用程序中是否有任何异常?如果是,请注意异常将CLEAN CORS 中间件设置的任何 CORS 标头
  • @Tseng,非常感谢 - 有趣的花絮。您能否详细说明或指出有关此的任何文档?我想我们一直在遇到这个问题

标签: angular asp.net-core cors


【解决方案1】:

builder.WithOrigins("http://localhost:4200/") 更改为

builder.WithOrigins("http://localhost:4200")

(删除了'/')

【讨论】:

  • 我觉得每次我建立一个新项目时都会在这个问题上花费数小时,而这最终就是原因所在。
【解决方案2】:

用 :

更改 API 中的行
app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowAnyCredentials());

确保您在 ConfigureServices() 中添加了 Services.AddCors(); 进行更改后停止服务器并再次运行。

【讨论】:

  • AllowAnyCredentials 在 ASP.NET Core 2.1 中显示为红色。是在另一个包里吗?
  • @JamesPoulose 应该只是 .AllowCredentials()
  • 这是唯一对我有用的解决方案。我在反应时遇到了这个问题
  • 重复代码后出现异常。 -- System.InvalidOperationException: 'CORS 协议不允许同时指定通配符(任何)来源和凭据。如果需要支持凭据,请通过列出各个来源来配置 CORS 策略。 -- 删除 .AllowCredentials 帮助了我
  • 这可能会导致 Asp.net core >3.0 出现异常:CORS 协议不允许同时指定通配符(任何)来源和凭据。如果需要支持凭据,则通过列出各个来源来配置 CORS 策略
【解决方案3】:

"WithOrigins" 期望一个数组,而不是一个字符串,所以也许这就是你的情况。 但是,Cors 在您的情况下工作的最低要求是:

在 Startup.cs 中添加 services.AddCors();services.AddMvc(); 之前还有:

string[] origins = new string[] { "http://localhost:4200" }; app.UseCors(b=>b.AllowAnyMethod().AllowAnyHeader().WithOrigins(origins));

app.UseMvc(your routes ...)之前再次添加

或者您真正需要的技术并不重要,只是添加一个“Access-Control-Allow-Origin”标头,其中包含服务器响应中的来源/来源的值,在 .Net core 2 中可以这样做这(在控制器中的任何方法中):
ControllerContext.HttpContext .Response .Headers .Add("Access-Control-Allow-Origin","http://localhost:4200");

或全局 - 您可以创建一个中间件,在源匹配时将此标头添加到所有响应中。 也可以在 Angular 6 和 .Net Core 2 中作为单独的应用程序使用。

【讨论】:

  • WithOrigins 需要 params string[] - 这意味着多个单独的字符串参数。单个string 参数就可以了。
【解决方案4】:

答案是正确的,但对于某些人来说,它可能不起作用,原因是语句的位置。必须在 useMvc()/addMvc 之前编写所有 CORS 相关语句。

在 Asp 网络核心中。语法看起来像

在 ConfigureServices 方法中

services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://localhost:4200");
                });
            });

// make sure the cors statement is above AddMvc() method.
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

在配置方法中

 app.UseCors(MyAllowSpecificOrigins);

 // make sure cors is above add UseMvc method.
 app.UseMvc();

这里的 MyAllowSpecificOrigins 只是一个策略名称,您可以在类的顶部定义

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

希望对你有帮助。

【讨论】:

    【解决方案5】:

    你可以通过在ConfigureServices中添加默认策略来配置Cors服务

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(options =>
                {
                    options.AddDefaultPolicy(
                        builder =>
                        {
                            builder.WithOrigins("http://localhost:4200");
                        });
                });
    
                .... add other services
            } 
    

    别忘了在Configure中添加UseCors

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                {
                    .. other middlewares 
                    app.UseCors();
                    app.UseRouting();
                    .. other middlewares 
        
                }
    

    【讨论】:

      【解决方案6】:

      同时尝试将AllowAnyMethod 添加到链中。

      builder.WithOrigins("http://localhost:4200/").AllowAnyMethod().AllowAnyHeader()
      

      【讨论】:

      • 同样的错误。就像我说的那样,我认为这与 Angular 方面有关,因为我实际上可以在 chrome 开发人员工具的网络选项卡中看到从服务器返回的数据。
      • 尝试用AnyOrigin替换WithOrigins
      • 大小写与给定格式有关。尝试另一种方式
      【解决方案7】:

      我在其他端口上提供角度服务,例如 :4200 或 :4300,具体取决于使用的端口数

      所以我已经在

      中配置了我的 asp.net 核心应用程序

      startup.cs

      文件以允许来自其他站点的 CORS

      public class Startup
      {
      
      
          readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
      
          public IConfiguration Configuration { get; }
      
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
      
      
      
              var config = new AutoMapper.MapperConfiguration(cfg =>
              {
                  cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
                  cfg.AddProfile(new ApplicationMappingProfile());
              });
              var mapper = config.CreateMapper();
              services.AddSingleton(mapper);
              services.AddCors(options =>
      {
          options.AddPolicy(MyAllowSpecificOrigins,
          builder =>
          {
              builder.WithOrigins("http://localhost:4200",
                                  "http://localhost:4300")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod();
          });
      });
              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      
      
              // Add EntityFramwork support for sqlServer
              services.AddEntityFrameworkSqlServer();
      
              //Add APplicationDbContext
              services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
      
              // In production, the Angular files will be served from this directory
              services.AddSpaStaticFiles(configuration =>
              {
                  configuration.RootPath = "ClientApp/dist";
              });
          }
      
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
      
      
              }
              else
              {
                  app.UseExceptionHandler("/Error");
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
              //create a service scope to get an ApplicationDbcontext instance using DI
              using (var serviceScope =
                  app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
              {
                  var dbContext =
                      serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
                  //create the db if it doesn;t exist
      
                  dbContext.Database.Migrate();
                  DbSeeder.Seed(dbContext);
              }
      
              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseSpaStaticFiles();
              app.UseCors(MyAllowSpecificOrigins); 
              app.UseMvc(routes =>
              {
                  routes.MapRoute(
                      name: "default",
                      template: "{controller}/{action=Index}/{id?}");
              });
      
              app.UseSpa(spa =>
              {
                  // To learn more about options for serving an Angular SPA from ASP.NET Core,
                  // see https://go.microsoft.com/fwlink/?linkid=864501
      
                  spa.Options.SourcePath = "ClientApp";
      
                  if (env.IsDevelopment())
                  {
                      spa.UseAngularCliServer(npmScript: "start");
                  }
              });
          }
      }
      

      请阅读asp.net coredocumentation

      【讨论】:

        猜你喜欢
        • 2019-07-02
        • 2018-10-13
        • 1970-01-01
        • 2019-10-27
        • 2018-03-27
        • 2018-11-20
        • 2019-02-01
        • 2019-06-02
        • 2018-06-09
        相关资源
        最近更新 更多