【发布时间】:2020-05-13 16:03:40
【问题描述】:
我在客户端有基于 Angular(7.2.1) 的 UI 的 Asp.Net Core(3) WebApi 项目。 当使用 Postman 或仅使用 URL 时,我可以使用 GET 和 POST 而不会出现任何特定错误。 当通过 Angular(Chrome\FireFox\IE Browser) 尝试相同的操作时,我收到以下错误。
zone.js:3243 OPTIONS http://localhost:8888/api/PaymentDetails 405 (Method Not Allowed)
ccess to XMLHttpRequest at 'http://localhost:8888/api/PaymentDetails' 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.
我将尝试分享尽可能多的代码来演示流程。
WebApi Startup.cs:
公共 IConfiguration 配置 { get; }
// 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("CorsPolicy",
builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer("Server=DESKTOP-KT0N2RN\\SQLEXPRESS;DataBase=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors("CorsPolicy");
}
WebAPI GET 方法:
[HttpGet]
public async Task<ActionResult<IEnumerable<PaymentDetail>>> GetPaymentDetails()
{
return await _context.PaymentDetails.ToListAsync();
}
客户端:
rootUrl: string = "http://localhost:8888/api";
getPaymentDetail()
{
console.log(`${this.rootUrl}/PaymentDetails`)
const headers = new HttpHeaders().set('Content-Type','application/json');
// headers.append('Access-Control-Allow-Origin', '*');
// headers.append('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
return this._http.get(`${this.rootUrl}/PaymentDetails`,{headers:headers});
}
【问题讨论】:
-
我更新了我的答案,希望它现在能正确解决你的问题
-
是的。这里的答案之一帮助我解决了这个问题。
app.UseCors()必须在 app.UseMvc(); 之前;
标签: c# angular asp.net-core asp.net-core-webapi