我正在尝试捕获错误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)
{
}
}
答案 0 :(得分:1)
您应在CORS.AllowPutMethod
方法上使用CORS.AllowPostMethod
而不是Put
。
[HttpPut("{id}")]
[EnableCors(CORS.AllowPutMethod)]
public void Put(int id, UserDTO currentUser)
{
}