Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular .NET CORE 2.0角5:允许Cors_Angular_Asp.net Core_Cors - Fatal编程技术网

Angular .NET CORE 2.0角5:允许Cors

Angular .NET CORE 2.0角5:允许Cors,angular,asp.net-core,cors,Angular,Asp.net Core,Cors,我在允许cors时遇到了一些麻烦。我已将服务器端设置为这样: app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader()); 在configure类的startup方法内部 当MyWebAPI被点击时,它将返回数据 然而,问题似乎与角度有关,如图所示,我得到以下错误: No 'Access-Control-Allow-Origin' header is present on

我在允许cors时遇到了一些麻烦。我已将服务器端设置为这样:

  app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader());
configure
类的
startup
方法内部

当MyWebAPI被点击时,它将返回数据

然而,问题似乎与角度有关,如图所示,我得到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
下面是我的AngularWebAPI调用

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)
    }

}

同时尝试将
AllowAnyMethod
添加到链中

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

更改了
builder.WithOrigins(“http://localhost:4200/“”

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

(删除了“/”)

使用以下命令更改API中的行:

app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowAnyCredentials());
确保添加了
Services.AddCors())
停止服务器并在进行更改后再次运行。

“WithOriginates”需要一个数组,而不是字符串,因此可能这就是您的情况。 但是,在您的情况下,Cors工作的最低要求是:

在Startup.cs中添加
services.AddCors()
before
services.AddMvc()以及:

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

再次将其添加到应用程序之前。使用MVC(您的路线…

或者您实际需要的并不重要技术是在服务器响应中添加一个“Access Control Allow Origin”头,该头的值为Origin/origins,在.Net core 2中可以这样做(在控制器中的任何方法中):
ControllerContext.HttpContext
.答复
.标题
.Add(“访问控制允许源”http://localhost:4200");

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

Am根据使用的端口数在其他端口(如:4200或:4300)上提供Angular服务

因此,我已在中配置了我的asp.net核心应用程序

startup.cs

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

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");
            }
        });
    }
}
公共类启动
{
只读字符串MyAllowSpecificCorigins=“\u MyAllowSpecificCorigins”;
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
var config=new AutoMapper.MapperConfiguration(cfg=>
{
cfg.DestinationMemberNamingConvention=新的LowerUnderscoreNamingConvention();
AddProfile(新的ApplicationMappingProfile());
});
var mapper=config.CreateMapper();
服务。AddSingleton(映射器);
services.AddCors(选项=>
{
options.AddPolicy(MyAllowSpecificCorigins,
生成器=>
{
建筑商。来源(“http://localhost:4200",
"http://localhost:4300")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//添加对sqlServer的EntityFramwork支持
services.AddEntityFrameworkSqlServer();
//添加APplicationDbContext

services.AddDbContext

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

在Asp net内核中。语法如下所示

在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);
在Configure方法中

 app.UseCors(MyAllowSpecificOrigins);

 // make sure cors is above add UseMvc method.
 app.UseMvc();
这里MyAllowSpecificCorigins只是一个策略名称,您可以在类的顶部定义

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

我希望这会有所帮助。

您可以通过在
ConfigureServices

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

            .... add other services
        } 
不要忘记在
Configure

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

同样的错误。就像我说的,我认为这与角度有关,因为我可以在chrome developer tools的“网络”选项卡中看到从服务器返回的数据。尝试将
替换为origins
,替换为
AnyOrigin
。案例与给定的格式有关。尝试其他方法您是否发现任何异常您的ASP.NET Core应用程序?如果是,请注意异常将清除CORS中间件设置的任何CORS头
AllowyCredentials
在ASP.NET Core 2.1中显示为红色。这是否在另一个包中?@JamesPoulose它应该是.AllowCredentials()这是唯一对我有效的解决方案。在重复代码后,我遇到了ReactGet异常的问题。-System.InvalidOperationException:“CORS协议不允许指定通配符(任何)同时列出源和凭据。如果需要支持凭据,请通过列出各个源来配置CORS策略。“--删除。AllowCredentials这可能导致Asp.net core>3.0中出现异常:CORS协议不允许指定通配符(任何)同时支持来源和凭据。如果需要支持凭据,请列出各个来源来配置CORS策略
WithOrigins
需要
params字符串[]
-这意味着有多个单独的字符串参数。一个单独的
字符串
参数就可以了。我觉得每次我建立一个新项目时,我都会花费数小时来解决这个问题,而这就是问题的原因所在。