简体   繁体   中英

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

I have a web api with asp.net core and an Asp.Net core webapp in which communication between them is not happening.

I did the api tests with Postman and everything worked fine, but when it's the web application this error is being returned: Access to XMLHttpRequest at 'http://localhost:15741/api/Home/CalculaEmprestimo' from origin 'http://localhost:39903' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I configured CORS on the web api but the error still persists.

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 Service

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

Can anyone help me resolve this?

  1. Make sure to include AllowAnyHeader() and AllowAnyMethod() before WithOrigins("...")
  2. If you're using Angular and you didn't change default port then you should rather use WithOrigins("http://localhost:4200");
  3. Sometimes you need to enable Cors on some browsers, try to run on multiple browsers and check if the problem persists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM