如何解决为什么我的服务器在 GET 预检请求中响应 Method Not Allowed 并说允许删除?
我有一个 .Net Core 3.1 Web API,它被设置为允许所有方法用于我的测试目的。 当我在特定端点上运行 HTTP GET 请求时,我得到 405 Method Not Allowed 并且响应标头显示 Allow: DELETE.
此控制器和我的其他控制器中的所有其他端点都按预期工作。
这是我的控制器代码:
[Authorize]
[Produces("application/json")]
[Route("api/User")]
public class UserAccountController : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[Route("ConfirmAccountEmail")]
protected override async Task<IActionResult> ConfirmAccountEmail(string token,string email)
{
// confirm email code here...
}
[HttpDelete("{id}")]
[Route("DeleteUserAccount")]
[Authorize(Roles = AdminToken)]
public override async Task<IActionResult> DeleteUserAccount([Fromroute] int id)
{
// user delete code here...
}
}
在我的 Startup.cs 中
public void Configure(IApplicationBuilder app,IWebHostEnvironment env,IHostApplicationLifetime appLifetime)
{
app.UseRouting();
app.UseCors(builder =>
{
builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod(); // just for testing
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoint(e =>
{
e.MapControllers();
));
}
我尝试将路由和 HTTP 类型更改为 POST(并将参数作为表单数据传递)。
我尝试删除那个 Delete 端点,在这种情况下我得到 404 Not Found。所以这让我相信,出于某种原因,控制器映射将一个路由绑定到我的另一条路由的 delete 方法,但我不明白为什么。
我觉得我遗漏了一些明显的东西,但我现在不知道那是什么。
感谢您的帮助!
解决方法
当我在特定端点上运行 HTTP GET 请求时,我收到 405 Method Not Allowed 并且响应标头显示 Allow: DELETE。
对于这个关于“动作定义”的文档,您可以找到:
控制器上的公共方法(带有 NonAction 属性的方法除外)都是操作。
请尝试在您的 protected
方法中将 public
修改为 ConfirmAccountEmail
,如下所示。
public async Task<IActionResult> ConfirmAccountEmail(string token,string email)
{
// confirm email code here...
,
通常您可以收到 CORS,但根本问题与 CORS 规则无关。我建议试试这个
[Authorize]
[Produces("application/json")]
[Route("api/User")]
public class UserAccountController : ControllerBase
{
[HttpGet]
[AllowAnonymous]
protected override async Task<IActionResult> ConfirmAccountEmail(string token,string email)
{
// confirm email code here...
}
[HttpDelete("{id}")]
[Authorize(Roles = AdminToken)]
public override async Task<IActionResult> DeleteUserAccount([FromRoute] int id)
{
// user delete code here...
}
}
即从操作方法中删除 Route
属性,然后像这样测试端点
GET https://localhost:4000/api/User
和 DELETE https://localhost:4000/api/User/1234
另一种选择是删除 HTTP 动词属性
[Authorize]
[Produces("application/json")]
[Route("api/User")]
public class UserAccountController : ControllerBase
{
[AllowAnonymous]
[Route("ConfirmAccountEmail")]
protected override async Task<IActionResult> ConfirmAccountEmail(string token,string email)
{
// confirm email code here...
}
[Route("DeleteUserAccount/{id}")]
[Authorize(Roles = AdminToken)]
public override async Task<IActionResult> DeleteUserAccount([FromRoute] int id)
{
// user delete code here...
}
}
然后像这样调用端点 GET https://localhost:4000/api/UserConfirmAccountEmail
和 DELETE https://localhost:4000/api/DeleteUserAccount/123
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。