ASP.NET 2.0 Web API有2个参数问题

Sim*_*gna 3 c# asp.net-core asp.net-core-webapi asp.net-core-routing

我编写了以下代码,以获取一个接受两个参数的Web API:

[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
    // GET: api/events/5
    [Route("api/[controller]/{deviceId}/{action}")]
    [HttpGet("{deviceId}/{action}")]
    public IEnumerable<CosmosDBEvents> Get(string deviceId,string action)
    {
        try
        {
            return null;
        }
        catch(Exception ex)
        {
            throw (ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下网址来调用它:

[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
    // GET: api/events/5
    [Route("api/[controller]/{deviceId}/{action}")]
    [HttpGet("{deviceId}/{action}")]
    public IEnumerable<CosmosDBEvents> Get(string deviceId,string action)
    {
        try
        {
            return null;
        }
        catch(Exception ex)
        {
            throw (ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。错误是404,找不到页面。

我还更改了代码,如下所示,但没有任何变化:

[Route("~/api/events/{deviceId}/{action}")]
[HttpGet("{deviceId}/{action}")]
public IEnumerable<CosmosDBEvents> Get(string deviceId,string action)
{
    try
    {
        return null;
    }
    catch(Exception ex)
    {
        throw (ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Kir*_*kin 6

使用ASP.NET Core路由时,有一些保留的路由名称。这是清单:

  • 行动
  • 区域
  • 控制者
  • 处理程序

如您所见,action它在列表中,这意味着您无法将其用于自己的目的。如果更改action为列表中未列出的其他内容,则可以使用:

[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
    [HttpGet("{deviceId}/{deviceAction}")]
    public IEnumerable<CosmosDBEvents> Get(string deviceId, string deviceAction)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我还从中删除了该[Route(...)]属性Get,这是多余的,因为您使用的[HttpGet(...)]属性还指定了路线。