【问题标题】:Setting up custom API route设置自定义 API 路由
【发布时间】:2016-07-22 06:25:35
【问题描述】:

在此处使用 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'.

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

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您的路线缺少 {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");
        }
    
        ...
    }
    

    【讨论】:

    • 果然。谢谢。
    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2015-06-04
    相关资源
    最近更新 更多