控制器路由上的 AmbiguousMatchException

AmbiguousMatchException on controller routes

我正在尝试在 .NET Core Web API 上构建一个基本的迷你项目,用于基本操作,例如:GET、POST、PUT、DELETE。

我的 WeatherForecastController 中有以下代码触发 AmbiguousMatchException:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Web;
using System.Net.Http;


namespace Webdemo.Controllers
{
    [ApiController]
    [Route("api/[controller]/[Action]")]
    public class WeatherForecastController : ControllerBase
    {
     static List<string> names = new List<string>()
         {
            "c","a","b"
         };
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return names;
        }
        [HttpGet]
        public string Get (int id) {
            return names[id];
        }
        [HttpPost]
        public void Post([FromBody]string value)
        {
            names.Add(value);
        }
        [HttpPut]
        public void Put(int id,[FromBody]string value)
        {
            names[id] = value;
        }
       [HttpDelete]
        public void Delete(int id) 
        {
            names.RemoveAt(id);
        }
    }
}

您的 Get 方法仅使用一组不同的参数匹配相同的端点。 您可以通过更改其中一个方法的名称来解决这个问题,例如,第二个 Get 方法可能会变成 GetSingle,因为它似乎通过其 names 列表中获取单个条目 id.

你可以这样做:

[HttpGet]
public string GetSingle (int id) 
{
    return names[id];
}

error: AmbiguousMatchException: The request matched multiple endpoints.

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return names;
    }
    [HttpGet]
    public string Get (int id) {
        return names[id];
    }

问题与上述代码有关,尝试为唯一标识符添加一个占位符变量,更改代码如下:

    // GET: api/<WeatherForecastController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return names;
    }
    // GET: api/<WeatherForecastController>/1
    [HttpGet("{id}")] //When this action is invoked, the value of "{id}" in the URL is provided to the method in its id parameter
    public string Get (int id) {
        return names[id];
    }

编辑:

关于使用 Asp.net 核心传递参数的文章 API:

Tutorial: Create a web API with ASP.NET Core

Parameter Binding in ASP.NET Web API

Multiple GET And POST Methods In ASP.NET Core Web API