【问题标题】:Calling a Get method in Web API with attribute routing使用属性路由在 Web API 中调用 Get 方法
【发布时间】:2014-05-20 13:51:47
【问题描述】:

我的WebApi.config 看起来像这样:

config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

这意味着它是configured to support both attribute based routing and conventional routing

然后创建了示例控制器:

[RoutePrefix("v1")]
public class Values1Controller : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };

    }

    [Route("products")]
    public string Get(int id)
    {
        return "value";
    }
}

当我调用http://localhost.domain/api/values1/v1/ 时,响应为value1, value2

但是,当我尝试调用http://localhost.domain/api/values1/v1/products/1 时(注意public string Get(int id) 方法上的products 属性路由,没有命中断点。

也就是说,如何调用public string Get(int id)方法,上面有属性路由Route(products)

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-web-api asp.net-mvc-routing


    【解决方案1】:

    您使用/v1/products?id=10 来点击操作public string Get(int id) 或将您的路线模板更改为[Route("products/{id}")] 以发出类似/v1/products/10 的请求

    请注意,与传统路由匹配的请求无法访问属性控制器/操作,这意味着您不能执行api/values/1 之类的操作来访问public string Get(int id) 操作

    【讨论】:

    • 太棒了。像魅力一样工作。非常感谢
    • http://localhost:portNum/v1/products?id=10 在路由属性为 [Route("products")] 时命中断点。 http://localhost:portNum/v1/products/10 在路由属性为 [Route("products/{id}")] 时命中断点。很好的解释@Kiran。谢谢。
    猜你喜欢
    • 2012-09-28
    • 2018-06-27
    • 2015-03-29
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2017-03-24
    • 2020-05-27
    • 2015-02-14
    相关资源
    最近更新 更多