我有一个基于 Angular(7.2.1) 的客户端的 Asp.Net Core(3) WebApi 项目。当使用 Postman 或直接使用 URL 时,我可以使用 GET 和 POST,没有任何错误。
但是当我试图在 Angular (Chrome\FireFox\IE 浏览器) 中尝试相同操作时,我会遇到以下错误:
zone.js:3243 OPTIONS http://localhost:8888/api/PaymentDetails 405 (Method Not Allowed)
从源 'http://localhost:4200' 到 'http://localhost:8888/api/PaymentDetails' 的 XMLHttpRequest 访问由于 CORS 策略而被阻止: 预检请求的响应不通过访问控制检查: 所请求的资源未包含 'Access-Control-Allow-Origin' 头。
我将尽可能共享代码以演示流程。
WebApi Startup.cs:
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.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()
之前。 - JumpIntoTheWater