【发布时间】:2021-08-02 23:49:15
【问题描述】:
我有一个带有 .NET Core 3.1 Web API 后端的 Vue 前端 Web 应用程序。我正在尝试对我的 API 进行 POST,但出现错误:
Access to XMLHttpRequest at 'https://myserver/myapi/address/4567' (redirected from 'http://myserver/myapi/address/4567') from origin 'http://myserver' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的网络 API 位于:https://myserver/myapi
我的 Vue Web 应用程序位于:https://myserver/mysite
在我的 .NET 的 Startup.cs 中:
private readonly string mySitePolicy = "mysite";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: mySitePolicy,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddSingleton<AddressRepository>();
services.AddSingleton<CustomerRepository>();
services.AddControllers();
services.Configure<IISServerOptions>(o =>
{
o.AutomaticAuthentication = false;
});
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseCors(policyName: mySitePolicy);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我已允许所有来源/标题/方法。我所有的 GET 请求都成功了,只有 POST 调用失败。是什么导致了错误?我该如何解决这个问题?
【问题讨论】:
-
你能发布整个配置部分吗?
-
嗨@Farid,确保对
UseCors的调用必须放在UseRouting之后,UseAuthorization之前。 -
@Sergey,我已经添加了整个 Configure 和 ConfigureServices 代码。
-
@Rena 我确实将 UseCors 放在了 UseRouting 之后。抱歉,我刚放假回来。
标签: asp.net-core cors asp.net-core-webapi