setup
- Windows 10
- Visual Studio 2017 Professional
- ASP.NET Core 2.2
我要做的
使用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答案
博客文章
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核心API。
要解决问题,请更正路由约束语法,将参数和datatype封闭在卷曲括号内[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);
}
}