.net - .net core 3.1 web api 中的多个 get 方法

标签 .net api asp.net-core .net-core

我正在尝试使用三个 get 方法创建一个非常基本的 Controller
以下是他们的三个 uri

  • GET/movies - 获取所有电影。
  • GET/movies?name={name}` - 查找与指定名称匹配的所有电影
  • Get/Movies/{Id} - 按 Id 查找电影

  • 我的 Controller 代码如下
    [Route("api/[controller]")]
    [ApiController]
    public class MoviesController : ControllerBase
    {
        private readonly IMoviesService moviesService;
    
        public MoviesController(IMoviesService moviesService)
        {
            this.moviesService = moviesService;
        }
        
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var result = await moviesService.GetMoviesAsync();
            return Ok(result);
        }
        
        [HttpGet]
        public async Task<IActionResult> GetByName([FromQuery(Name = "name")] string name)
        {
            var result = await moviesService.GetMoviesByNameAsync(name);
            return Ok(result);
        }
    
        [HttpGet("{Id}", Name = "GetById")]
        public async Task<IActionResult> GetById(Guid Id)
        {
            var result = await moviesService.GetMovieById(Id);
            return Ok(result);
        }       
    
    }
    
    当我通过 api/movies/31234567-89ab-cdef-0123-456789abcdef 向 GetById 发送请求时,它就起作用了
    但是对于 api/moviesapi/movies?name=Test 我得到以下错误The request matched multiple endpoints. Matches: MoviesController.Get and MoviessController.GetByName任何人都可以建议我考虑到最佳实践,在 web api .net core 3.1 中实现这种场景的最佳方法是什么?

    最佳答案

    您的 GetGetByName 操作没有为它们提供属性路由,并且都与“api/Movies”匹配。为了解决这个问题,您还需要为这些操作中的至少一个添加一个路由模板。
    一个可能的解决方案是:

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var result = await moviesService.GetMoviesAsync();
        return Ok(result);
    }
    
    [HttpGet]
    [Route("{name}")]
    public async Task<IActionResult> GetByName([FromRoute] string name)
    {
        var result = await moviesService.GetMoviesByNameAsync(name);
        return Ok(result);
    }
    
    请注意,此处具有特定名称的电影的 url 不再是/movies?name={name},而是/movies/{name}。
    如果您绝对希望保留 URL/movies?name={name},您可以将 GetGetByName 操作合并到一个接受查询字符串参数 name 并根据其值执行您的逻辑的操作中。

    关于.net - .net core 3.1 web api 中的多个 get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137002/

    相关文章:

    c# - 为什么 ? : operator does not work with nullable<int> assignation?

    .net - 使用 EventLog 对象会导致安全漏洞?

    c# - Windows 服务

    java - 如何从 Python 与 Java 交互

    javascript - 在浏览器中加载node-spotify或spotify-web Node 模块

    c# - 如何让下拉菜单默认为空白

    c# - 使用左连接 lambda 的 Entity Framework 加载数据

    asp.net - 如何在 Visual Studio 2017 中使用 NPM 并安装包?

    .net - 为什么我的网站项目无法适应.NET 3.5?

    javascript - 即使在 React 中正确导入后也不包含默认导出