如何使用属性路由“重载”操作?

时间:2017-10-29 20:06:13

标签: asp.net asp.net-mvc asp.net-core asp.net-core-mvc

我有两个具有相同名称的操作,但是一个是第一个重载,它接受第一个重载没有的int参数:

[HttpGet("Read")]
[Produces(typeof(IEnumerable<Client>))]
public async Task<IActionResult> Read()
...
[HttpGet("Read/{id}")]
[Produces(typeof(Client))]
public async Task<IActionResult> Read(int id)

我已经尝试了所有我知道的方法来正确定义路由属性模板,并使用参数形成正确的URL以调用第二个操作。每次尝试使用我的代码和PostMan来调用此操作都会产生404。

整个控制器看起来像这样:

[Route("api/[controller]")]
[Produces("application/json")]
public class ClientsController : Controller
{
    private readonly IDataService _clients;

    public ClientsController(IDataService dataService)
    {
        _clients = dataService;
    }

    [HttpPost("Create")]
    [Produces(typeof(int))]
    public int Post([Bind("GivenName,FamilyName,GenderId,DateOfBirth,Id")] Client client)
    {
        var ret = _clients.Create(client);
        return ret;
    }

    [HttpGet("Read")]
    [Produces(typeof(IEnumerable<Client>))]
    public async Task<IActionResult> Read()
    {
        var clients = await _clients.ReadAsync();
        return Ok(clients);
    }

    [HttpGet("Read/{id}")]
    [Produces(typeof(Client))]
    public async Task<IActionResult> Read(int id)
    {
        var client = await _clients.ReadAsync(id);
        if (client == null)
        {
            return NotFound();
        }

        return Ok(client);
    }

    [HttpPut("Update")]
    public void Put([Bind("GivenName,FamilyName,GenderId,DateOfBirth,Id")] string json)
    {
        // NB Edit isn't saving.
        var client = JsonConvert.DeserializeObject<Client>(json);
        _clients.UpdateAsync(client);
    }

    [HttpDelete("Delete/{id:int}")]
    public void Delete(int id)
    {
    }
}

0 个答案:

没有答案