c# - .NET core OPTIONS 请求返回 405 错误
问题描述
我需要将 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。
启动.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();
}
}
}
我的控制器.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 处理程序,但这似乎是一个非常糟糕的解决方案。
解决方案
你需要修改你的类 StartUp.cs,试着把代码像这样......
public void ConfigureServices (IServiceCollection services) {
services.AddLogging ();
services.AddCors (); // just adding the cors to the services
services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_2_2);
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env) {
// global cors policy
app.UseCors (x => x
.AllowAnyOrigin ()
.AllowAnyMethod ()
.AllowAnyHeader ()); // configure CORS
app.UseHttpsRedirection ();
app.UseMvc ();
}
并且 CORS 必须对您的所有 Apicontroller 正常工作。
如果错误代码 405 继续出现:表示您没有正确调用端点。
请验证并给我有关结果的反馈。
推荐阅读
- sql - 使用 IF/ELSE 逻辑在 SQL 查询中创建新列?
- java - 为什么我的程序中的 ArrayList 插入速度比 LinkedList 快?
- ubuntu - `DllNotFoundException: libc` 尝试在 snap 包中运行单声道应用程序时
- oracle - Visual Basic 编译的可执行数据库连接问题
- charts - Highchart 甘特图 Navigator 颜色
- geolocation - Convert CEP (Brazilian ZIP code) in latitude and longitude
- python - Python/MySQL - 将 MySQL 数据导出到 Excel
- python - 使每个 Y 值对应 pyqtgraph 中的一个 X 值
- c# - 将 IAsyncEnumerable 转换为 List
- drake - 使用二阶系统模拟控制回路时的段错误