无法从angular 8应用程序访问webapi

时间:2019-08-19 22:50:16

标签: angular asp.net-core asp.net-core-webapi

我已经实现了一个asp.net核心网络api,端点似乎工作正常。我正在通过本地Web服务器运行webapi。我也可以通过邮递员访问api。我已经实现了Angular 8应用程序。尝试访问api端点时出现未知错误。我最初以为是cors问题,并在控制器中启用了cors,但仍然遇到相同的问题。有人可以告诉我问题出在哪里吗

webapi ur为http://localhost:56676/api/customers,角度应用程序网址为http://localhost:4200/customer

正在收到的错误消息是

从原点“ http://localhost:56676/api/customers/”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。

角度代码

CustomerComponent

ngOnInit() {
      this.customers$ = this.customerService.getCustomers()
          .pipe(
              catchError(err => {
                 this.errorMessage = err;
                 return EMPTY;
              })
          )
  }

客户界面

interface ICustomer {

        customerId : string;
        companyName : string;
        contactName : string;
        contactTitle : string;
        address : string;
        city : string;
        region : string;
        postalCode : string;
        country : string;
        phone : string;
        fax : string;

}

CustomerService

export class CustomerService {

  constructor(private smartTrCommonService:  SmartTrCommonService) { }

  getCustomers() : Observable<ICustomer[]>{
    return this.smartTrCommonService.httpGet('/api/customers/');
  }
}

CommonService

export class SmartTrCommonService {

    webApplication = this.getApiLocation();

    private getApiLocation() {
        const port = location.port ? ':56676' : '';
        return location.protocol + '//' + location.hostname + port;
    }

    constructor(private httpClient: HttpClient) { }

    httpGet(url: string): Observable<any> {
        return this.httpClient.get(this.webApplication + url, httpPostOptions)
            .pipe(map((response: Response) => {
                return response;
            }), catchError(error => {
                this.onError(error);
                return Promise.reject(error);
            }));
    }
}

Asp.Net核心

[EnableCors("AllowOrigin")]
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {

        ICustomerRepository _customersRepository;


        public CustomersController(ICustomerRepository customersRepository)
        {
            _customersRepository = customersRepository;
        }

        [HttpGet]
        [EnableCors("AllowOrigin")]
        public async Task<IActionResult> Get()
        {
            try
            {
                var customers = await _customersRepository.GetAllCustomers();
                if (customers == null)
                {
                    return NotFound();
                }

                return Ok(customers);
            }
            catch
            {
                return BadRequest();
            }
        }
}

startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddSwaggerGen(c =>
            {

            });


            services.AddDbContext<NorthwindContext>(item => item.UseSqlServer(Configuration.GetConnectionString("NorthwindDBConnection")));
            services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.WithOrigins("http://localhost:4200"));
        });

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

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);



            services.AddScoped<ICustomerRepository, CustomerRepository>();
        }

        // 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
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
               app.UseCors(options => options.WithOrigins("http://localhost:4200"));
            app.UseCors("MyPolicy");
            app.UseHttpsRedirection();
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API name"); });
            app.UseMvc();
        }

更新的启动文件

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)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddSwaggerGen(c =>
            {

            });


            services.AddDbContext<NorthwindContext>(item => item.UseSqlServer(Configuration.GetConnectionString("NorthwindDBConnection")));

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

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

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);



            services.AddScoped<ICustomerRepository, CustomerRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseOptions();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCors("AllowOrigin");

            app.UseHttpsRedirection();
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API name"); });
            app.UseMvc();
        }
    }

2 个答案:

答案 0 :(得分:0)

我认为您遇到了CORS错误:对于开发,您可以:

  • 在您的API中修复它(接受您的主机/ ip地址)
  • 使用CORS插件

选中this

答案 1 :(得分:0)

尝试像这样配置您的CORS策略:

/<link (?=[^>]*type="image\/x-icon")[^>]* href="([^"]+)" [^>]*>/