c# - 具有 2 个参数问题的 ASP.NET 2.0 Web API

标签 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);
        }
    }
}

我尝试使用以下 url 调用它:

https://localhost:44340/api/events/abcde/indice

但它不起作用。错误是 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);
    }
}

我做错了什么?

最佳答案

使用ASP.NET Core路由时,有几个Reserved routing names .这是列表:

  • action
  • area
  • controller
  • handler
  • page

如您所见,action 在列表中,这意味着您不能将其用于您自己的目的。如果您将 action 更改为不在列表中的其他内容,它将起作用:

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

请注意,我还从 Get 中删除了 [Route(...)] 属性,由于您使用了 [ HttpGet(...)] 还指定路由的属性。

关于c# - 具有 2 个参数问题的 ASP.NET 2.0 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217516/

相关文章:

c# - 如何编写具有某些功能的 DataTemplate 作为资源

c# - XAML 定义的 StoryBoard 在 C 中调用时抛出空指针

c# - 健康检查端点生成的 HealthReport 对象结构卡住 Swagger 文档页面

angular - .net 核心 2.2 和 Angular 7 : IFormFile in file upload controller is always null

c# - 创建新用户时添加声明

c# - 使用 Xamarin.Forms 创建 ASP.Core WebAPI

c# - 估算 Web 应用时间的经验法则

c# - 如何在 WebBrowser 控件 C# 中突出显示特定单词

docker - 转发客户端的请求头

asp.net-core - Code First 中的 Identity 和 Mysql - 指定的键太长;最大 key 长度为 1000 字节