无法从angular 8应用程序访问webapi [英] Unable to access the webapi from angular 8 application
问题描述
我已经实现了一个asp.net核心网络api,端点似乎工作正常.我正在通过其本地网络服务器运行webapi.我也可以通过邮递员访问api.我已经实现了Angular 8应用程序.尝试访问api端点时出现未知错误.我最初以为是cors问题,并在控制器中启用了cors,但仍然面临相同的问题.有人可以告诉我问题出在哪里吗
I have implemented an asp.net core web api and the endpoints seems to work fine. I am running the webapi via its local webserver. I am able to access the api via postman as well. I have implemented an Angular 8 application. I am getting an unknown error while trying to access the api endpoint. I initially thought it is cors issue and enabled cors in my controller but still facing the same problem. Could somebody tell me what the problem could be
webapi ur是 http://localhost:56676/api/customers 和有角度的应用程序网址为 http://localhost:4200/customer
The webapi ur is http://localhost:56676/api/customers and the angular application url is http://localhost:4200/customer
正在收到的错误消息是
通过" http://localhost:56676/api/customers/"访问XMLHttpRequest来自来源" http://localhost:4200 "已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有"Access-Control-Allow-Origin"标头.
Access to XMLHttpRequest at 'http://localhost:56676/api/customers/' from origin 'http://localhost:4200' 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.
角度代码
CustomerComponent
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
CustomerService
export class CustomerService {
constructor(private smartTrCommonService: SmartTrCommonService) { }
getCustomers() : Observable<ICustomer[]>{
return this.smartTrCommonService.httpGet('/api/customers/');
}
}
CommonService
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
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();
}
}
推荐答案
尝试配置您的CORS策略,例如:
Try to configure your CORS policy like:
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
这篇关于无法从angular 8应用程序访问webapi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!