【发布时间】:2019-09-22 19:23:12
【问题描述】:
设置
- Windows 10
- Visual Studio 2017 专业版
- ASP.Net Core 2.2
我要做什么
针对我的 Web API 中使用 PATCH 动词的控制器方法运行集成测试
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);
}
到目前为止我做了什么
我发现在尝试使用PUT、PATCH 或DELETE 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}")]来指定路由约束吗?另外,您是否尝试过使用 POSTMAN 或 Fiddler 测试您的端点? -
Facepalm,我已经看了 2 天了!!谢谢你 Moshin。
标签: c# asp.net-core