设置自定义API路由

时间:2016-07-21 22:22:16

标签: c# asp.net

在此处使用ASP.NET 4.6。

我有一个控制器:

public class ComputerController : ApiController
{
    ...

    [HttpGet]
    [Route("api/computer/ping")]
    public IHttpActionResult Ping(int id)
    {
        return Ok("hello");
    }

    ...
}

主要来自this answer(看看MSTdev的答案),我在WebApiConfig.cs中有这个:

// So I can use [Route]?
config.MapHttpAttributeRoutes();
// handle the defaults.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

路线不起作用。我总是得到

No HTTP resource was found that matches the request URI
'http://localhost:29365/api/computer/ping'.

这似乎是一个简单的问题,但我仍然难过。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

您的路线缺少{id}参数。 实施例

[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }

您的控制器应如下所示:

public class ComputerController : ApiController
{
    ...

    [HttpGet]
    [Route("api/computer/ping/{id}")]
    public IHttpActionResult Ping(int id)
    {
        return Ok("hello");
    }

    ...
}