Asp.Net Core Api 和 Asp.Net Webapp 与 Angular 之间的连接问题

Connection problems between Asp.Net Core Api and Asp.Net Webapp with Angular

我有一个具有 asp.net 核心的网络 api 和一个 Asp.Net 核心网络应用程序,它们之间没有进行通信。

我用 Postman 进行了 api 测试,一切正常,但当它是 Web 应用程序时,会返回此错误: 从来源 'http://localhost:39903' 访问 'http://localhost:15741/api/Home/CalculaEmprestimo' 处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin' header 出现在请求的资源上。

我在网络上配置了 CORS api,但错误仍然存​​在。

API

  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddCors(options =>
      {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                            builder.WithOrigins("http://localhost:39903");
                          });
      });

      services.AddControllers();
      services.AddSwaggerGen(c =>
      {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
      });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
      }

      app.UseRouting();
      app.UseCors(MyAllowSpecificOrigins);

      app.UseAuthorization();

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

Angular 服务

import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmprestimo } from '../Model/emprestimo.interface';
import { IEmprestimoResult } from '../Model/emprestimoresult.interface';
import { fromEvent, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { strict } from 'assert';

@Injectable({
  providedIn: 'root'
})
export class EmprestimoService {

  constructor(private http: HttpClient) { }

  postEmprestimo(pEmprestimo: IEmprestimo): Observable<IEmprestimoResult>
  {
    const headers = { 'Content-Type': 'application/json', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Connection':'keep-alive' };
    const body = {
                    "parcelas": pEmprestimo.parcelas,
                    "valorParcelas": pEmprestimo.valorParcelas,
                    "valorEmprestimo": ""
                  };

    var result = this.http.post<IEmprestimoResult>('http://localhost:15741/api/Home/CalculaEmprestimo', body);
    return result;
  }
}

谁能帮我解决这个问题?

  1. 确保在 WithOrigins("...") 之前包含 AllowAnyHeader() 和 AllowAnyMethod()
  2. 如果您使用 Angular 并且没有更改默认端口,那么您应该使用 WithOrigins("http://localhost:4200");
  3. 有时您需要在某些浏览器上启用 Cors,尝试在多个浏览器上运行并检查问题是否仍然存在。