Cha*_*son 6 c# cors http-status-code-405 .net-core
我需要向 .NET core 3.1 API 添加 CORS 支持(是 2.2,但我决定同时更新)。我以为这会很容易。这里的文档: https: //learn.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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
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});
}
Run Code Online (Sandbox Code Playgroud)
我已经经历了几次迭代,也在这里查看:https://learn.microsoft.com/en-us/aspnet/core/security/cors ?view=aspnetcore-3.1#enable-cors-with-endpoint-routing 。我可能错过了一些小而简单的东西。我可以在所有控制器中添加手动 OPTIONS 处理程序,但这似乎是一个非常糟糕的解决方案。
小智 5
你需要修改你的类 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);
}
Run Code Online (Sandbox Code Playgroud)
public void Configure (IApplicationBuilder app, IHostingEnvironment env) {
// global cors policy
app.UseCors (x => x
.AllowAnyOrigin ()
.AllowAnyMethod ()
.AllowAnyHeader ()); // configure CORS
app.UseHttpsRedirection ();
app.UseMvc ();
}
Run Code Online (Sandbox Code Playgroud)
并且 CORS 必须对您的所有 Api 控制器正确工作。
如果错误代码405继续出现: 表示您没有正确调用端点。
请验证并向我反馈结果。
| 归档时间: |
|
| 查看次数: |
5257 次 |
| 最近记录: |