簡體   English   中英

Angular 和 Asp.net 內核 CORS 問題

[英]Angular and Asp.net core CORS issue

這個問題我已經有一段時間了,我已經嘗試了所有可能的解決方案,我的 asp.net 核心服務器啟用了 CORS,代碼如下,但有時我會收到 No 'Access-Control-Allow-Origin' 的錯誤

我的生產 API 托管在 windows 服務器上的 IIS 上

有什么辦法可以調試這個嗎?

CORS 策略已阻止從源“DOMAIN”訪問“Production_API”處的 XMLHttpRequest:請求的資源上不存在“Access-Control-Allow-Origin”Z099FB995346F31C749F6E40DB0F395。 zone.js:3372

獲取 APICALL 網絡::ERR_FAILED

在 zone.js 中,它說它有一個錯誤“加載資源失敗:net::ERR_FAILED”

 sendNative.apply(target, data.args);
 target[XHR_SCHEDULED] = true;
 return task;

ASP.net 內核 CORS 代碼

    public void ConfigureServices(IServiceCollection services)
    {
       

        services.AddCors(options =>
        {
            options.AddPolicy("AllowEverything",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<ApplicationDbContext>(options =>
           options.UseSqlServer(
               Configuration.GetConnectionString("DefaultConnection")));

        

        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.SignIn.RequireConfirmedEmail = false;
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();

        services.AddAuthentication(
          option =>
          {
              option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
              option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
          })
       .AddJwtBearer(options =>
       {
           options.TokenValidationParameters.ValidateIssuer = true;
           options.TokenValidationParameters.ValidateIssuerSigningKey = true;
           options.TokenValidationParameters.ValidateLifetime = true;
           options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]));
           options.TokenValidationParameters.ValidIssuer = Configuration["Tokens:Issuer"];
           options.TokenValidationParameters.ValidAudience = Configuration["Tokens:Audience"];
       });
    

       

        services.AddTransient<Services.IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.Configure<SMSoptions>(Configuration);

        

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        var mappingConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MappingProfile());
        });

        IMapper _mapper = mappingConfig.CreateMapper();
        services.AddSingleton(_mapper);
    }

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       app.UseCors("AllowEverything");
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            //app.UseHsts();
        }




        app.UseCors("AllowEverything");


        app.UseAuthentication();
        
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
     }

AllowAnyOrigin()僅在不使用AllowCredentials()時有效

您必須使用.WithOrigins("http://example.com","http://www.contoso.com"); 使用憑據時。

你也使用app.UseCors(AllowEverything); 在你的

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

我嘗試了很多不同的解決方案,最后我發現 http 攔截器上有一個未知錯誤,我認為當系統在 CPU 使用率達到最大值時會發生這種情況,因為 angular 無法完成調用和它進入未知錯誤,因為 CPU 沒有處理它的空間。 請讓我知道這是否有意義或在繁重的應用程序中可能發生的事情。

謝謝

嘗試 x 是策略:

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:****"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM