【问题标题】:Catch and repsonse custom json on 405 HTTP error - ASP.NET CORE API捕获并响应 405 HTTP 错误的自定义 json - ASP.NET CORE API
【发布时间】:2018-12-19 23:23:54
【问题描述】:

我正在尝试捕获错误 405 以启动个性化响应,但我做不到。当我调用该方法时,我得到一个 CORS 问题的一般错误

//Startup.cs
servicesCollection.AddCors(x =>
{
    x.AddPolicy(CORS.AllowPutMethod,
        policyBuilder =>
        {
            policyBuilder.WithOrigins("http://localhost:4200")
                .WithMethods(HttpMethods.Put).AllowAnyHeader();
        });
    x.AddPolicy(CORS.AllowPostMethod,
        policyBuilder =>
        {
            policyBuilder.WithOrigins("http://localhost:4200")
                .WithMethods(HttpMethods.Post).AllowAnyHeader();
        });
});

public static class CORS
{
    public const string AllowPutMethod = nameof(AllowPutMethod);

    public const string AllowPostMethod = nameof(AllowPostMethod);
}

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    // PUT: api/User/5
    [HttpPut("{id}")]
    [EnableCors(CORS.AllowPostMethod)] <=== ERROR HERE!!!
    public void Put(int id, UserDTO currentUser)
    {
    }

}

【问题讨论】:

    标签: asp.net-core asp.net-core-2.0 asp.net-core-webapi asp.net-core-2.1


    【解决方案1】:

    您应该在 Put 方法上使用 CORS.AllowPutMethod 而不是 CORS.AllowPostMethod。

            [HttpPut("{id}")]
        [EnableCors(CORS.AllowPutMethod)] 
        public void Put(int id, UserDTO currentUser)
        {
    
        }
    

    【讨论】:

    • 你好,我也是故意要捕捉错误“405 Methos not allowed”,但我做不到。
    • 对于Method not allowed的错误,我认为是CORS的bug,我已经在这里提交了[github.com/aspnet/Home/issues/3327]。
    猜你喜欢
    • 2019-08-03
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多