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

时间:2019-05-04 14:24:05

标签: c# asp.net-core

设置

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

我要做什么

针对使用PATCH动词的Web API中的控制器方法运行集成测试

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的问题。

1 个答案:

答案 0 :(得分:3)

要解决此问题,请更正路径约束语法,将参数和数据类型放在大括号[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);
    }
}