【发布时间】:2020-05-02 18:39:18
【问题描述】:
我需要将 CORS 支持添加到 .NET core 3.1 API(是 2.2,但我决定同时更新)。我以为这很容易。这里的文档:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 看起来很简单。我想在所有端点上支持相同的 CORS 策略。所以,我想我可以不理会我的控制器,只需对 startup.cs 进行更改。我错过了什么?
我有一个 POST 端点,但 OPTIONS 请求返回 405 错误。我认为 CORS 中间件应该处理请求,因此我根本不必考虑控制器内部的 CORS。
Startup.cs
namespace MyAPI
{
public class Startup
{
readonly String ALLOW_ALL = "AllowAll";
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.Configure<IISOptions>(options =>
// {
// options.AutomaticAuthentication = true;
// });
services.AddLogging();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
// .AllowCredentials();
});
});
services.AddMvc(MvcOptions => MvcOptions.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
// if (env.IsDevelopment())
// {
// app.UseDeveloperExceptionPage();
app.UseCors();
// }
app.UseEndpoints(endpoints => endpoints.MapControllers());
app.UseMvc();
}
}
}
MyController.cs
namespace MyProj.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FacilitiesController : ControllerBase
{
public FacilitiesController()
{
}
[HttpPost]
public JsonResult FloorPlanURL([FromBody] UniqueFloor theFloor)
{
<stuff happens>
return new JsonResult(new {success = true, url = out});
}
我已经经历了几次迭代,也看这里:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-endpoint-routing。我可能错过了一些小而简单的东西。我可以在所有控制器中添加手动 OPTIONS 处理程序,但这似乎是一个非常糟糕的解决方案。
【问题讨论】:
-
你好。我正在经历完全相同的事情。你解决过这个问题吗?
-
确保您的 OPTIONS 请求同时具有
Access-Control-Request-Method和Origin标头,否则中间件将拒绝 405。 -
你好。我正在经历完全相同的事情。你解决过这个问题吗?
标签: c# .net-core cors http-status-code-405