asp.net core [CreatedAtAction] web api HttpPost 返回 CreatedAtAction 时报错: No route matches the supplied values

.net core 版本: 3.1
vs: Microsoft Visual Studio Community 2019 Version 16.4.1

应该不是core版本或者vs version的问题, 我按照官方文档 https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio#examine-the-posttodoitem-create-method 写出的demo是可以正常返回 status code 201.

web api:

[HttpGet("{id}")]
public async Task<IActionResult> GetPostByIdAsync(Guid id)
{
    try
    {
        var postResponse = await _postService.GetPostAsync(id);
        if (!postResponse.IsSuccess)
        {
            return ServerError(postResponse);
        }
        var post = postResponse.Item;

        if (post != null)
                {
                    return new OkObjectResult(post);
                }
        return NotFound();
    }
    catch (Exception e)
    {
        logger.LogError(e, "Error getting post list.");
        return new StatusCodeResult(statusCode: StatusCodes.Status500InternalServerError);
    }
}

[HttpPost]
[Authorize]
public async Task<IActionResult> CreatePostAsync([FromBody] Post model)
{
    if (model.Id == null)
    {
        return Problem("the model id should not be null, please check it.", null, StatusCodes.Status500InternalServerError);
    }
    var request = new EditPostRequest(model.Id)
            {
                ...
            };

    var response = await _postService.CreateNewPostAsync(request);

    if (response.IsSuccess)
    {
        var action = CreatedAtAction(nameof(GetPostByIdAsync), new { id = model.Id }, model);
        return action;
    }
    else
    {
        return ServerError(response);
    }

}

startup.cs类中并无特殊之处, 请问大神, 我使用 postman或者 swagger测试 [httpPost] 方法为什么会报错No route matches the supplied values.

我自己查了一些底层代码, 底层 CreatedAtActionResult 类里面 OnFormatting 会在写http response时执行, 这个方法如果url没有生成会抛出invalidoperation exception, 并且error message在资源文件里面的内容和我们的一样, key是NoRoutesMatched. 但是执行了底层代码的单元测试以后也没有发现什么问题. 应该是我的code的问题, 看不出哪里出错了. 请教大家.

update at 2020-1-3 14:26:48 贴几个图如下:

asp.net core [CreatedAtAction] web api HttpPost 返回 CreatedAtAction 时报错: No route matches the supplied values
asp.net core [CreatedAtAction] web api HttpPost 返回 CreatedAtAction 时报错: No route matches the supplied values

最佳答案

经过修改 post controller 中的 GetPostByIdAsync(Guid id) => GetPost(Guid id) 后不再报错:

asp.net core [CreatedAtAction] web api HttpPost 返回 CreatedAtAction 时报错: No route matches the supplied values
[HttpGet("{id}")]
        public async Task<IActionResult> GetPost(Guid id)
        {}

 [HttpPost]
        [Authorize]
        public async Task<IActionResult> CreatePostAsync([FromBody] Post model)
        {
       var action = CreatedAtAction(nameof(GetPost), new { id = model.Id }, model);
        }

暂时不清楚底层 urlhelper获取路由时为什么匹配不到原来的名字, 需要进一步调查

详细问题及其他答案请点击原文链接

原文出处:博客园

原文链接:https://q.cnblogs.com/q/125218/

本文观点不代表Dotnet9立场,转载请联系原作者。

发表评论

登录后才能评论