在405 HTTP错误上捕获并响应自定义json-ASP.NET CORE API

时间:2018-07-11 20:19:03

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

我正在尝试捕获错误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)
    {
    }

}

HTTP ERROR (Angular 6)

Response

1 个答案:

答案 0 :(得分:1)

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

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

    }