.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.
update at 2020-1-3 14:26:48 贴几个图如下:
经过修改 post controller 中的 GetPostByIdAsync(Guid id) => GetPost(Guid id) 后不再报错:
[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获取路由时为什么匹配不到原来的名字, 需要进一步调查
Controller 有没有加属性路由 [Route]
?
加了:
[ApiController]
[Route("api/[controller]")]
[AllowAnonymous]
public class PostController : DennisController
{}
[Route("api/[controller]")]
[ApiController]
public class DennisController : ControllerBase
{}
CreatePostAsync 上面 加上路由名称。[Route("CreatePostAsync")]
你应该用的默认路由,不会自动搜索到Action
请问是这样吗?
[HttpPost]
[Route("CreatePostAsync")]
[Authorize]
public async Task<IActionResult> CreatePostAsync([FromBody] Post model)
{}
我之前遇到和你一样的报差,后来我在Startup文件里,Configure方法下的UseEndpoints加了endpoints.MapDefaultControllerRoute();就解决了
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
});
刚又看了下,虽然返回没有报错了,但是Response headers里面的location不正确了,不是Route里指定的路由,而是默认的[Controller]/[Action]
以前做过另外一个项目,使用的是asp.net core MVC,凡是Controller里出现Async结尾的Action方法名,都找不到路由
@Alan_Liu: 感谢感谢! 我还写了一个Action 名为 GetPostAsync 获取所有 posts. 这个是可以通过postman发送http request请求server通过路由匹配到的. 只是没试过 CreatedAtAction 能不能, 有可能底层确实对 Async后缀的action支持的有问题
@YanyuWu: 我把异步的命名都改过来就对了,果然是个玄学问题。。。