gpt4 book ai didi

c# - 不允许使用 ASP.NET Core 2.2 WebAPI 405 方法

转载 作者:太空狗 更新时间:2023-10-30 00:47:44 24 4
gpt4 key购买 nike

设置

  • Windows 10
  • Visual Studio 2017 专业版
  • ASP.Net Core 2.2

我想做什么

针对我的 Web API 中使用 PATCH 动词的 Controller 方法运行集成测试

MyController.cs

namespace FluidIT.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
private readonly IMediator _mediator;
private readonly IMyQueries _myQueries;

public JobsController(IMediator mediator, IMyQueries myQueries)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_myQueries = myQueries ?? throw new ArgumentNullException(nameof(myQueries));
}

// PATCH: api/v1/my/{id}
[Route("id:int")]
[HttpPatch]
public async Task<IActionResult> RemoveMeAsync(int id)
{
bool commandResult = false;

try
{
commandResult = await _mediator.Send(new RemoveMeCommand(id));
return NoContent();
}
catch (NotFoundException)
{
return NotFound(id);
}
}
}
}

MyIntegrationTest.cs

[Fact]
async Task Patch_MyAsync_WhenIdNotFound_ReturnsNotFoundStatusCode()
{
// Arrange
var request = new HttpRequestMessage()
{
RequestUri = new Uri($"{_fixture.Client.BaseAddress}{_baseRoute}/1"),
Method = HttpMethod.Patch,
Headers =
{
{ HttpRequestHeader.ContentEncoding.ToString(), Encoding.UTF8.ToString() },
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
}
};

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

到目前为止我做了什么

我发现在尝试使用 PUTPATCHDELETE http 动词时,这是相当常见的情况。我还看到将以下内容添加到 web.config 文件以从 IIS 中删除 webDAV 模块是建议的解决方案

Stackoverflow answer
A blog post

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
</configuration>

但是,正如您可能已经猜到的那样,此解决方案对我不起作用。我的测试返回一个 405 MethodNotAllowed 响应。

关于这个主题的大部分信息似乎都是很久以前的,所以我想我应该在这里专门针对 ASP.NET Core API 提出这个问题。

最佳答案

要解决此问题,请更正路由约束语法,将参数和数据类型括在花括号内 [Route("{id:int}")]

[Route("{id:int}")]
[HttpPatch]
public async Task<IActionResult> RemoveMeAsync(int id)
{
bool commandResult = false;

try
{
commandResult = await _mediator.Send(new RemoveMeCommand(id));
return NoContent();
}
catch (NotFoundException)
{
return NotFound(id);
}
}

关于c# - 不允许使用 ASP.NET Core 2.2 WebAPI 405 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com