微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net Web Api路由不工作

这是我的路由配置:
config.Routes.MapHttpRoute(
    name: "ActionApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }
);

而且,这是我的控制器:

public class ProductsController : ApiController
{
    [AcceptVerbs("Get")]
    public object GetProducts()
    {
       // return all products...
    }

    [AcceptVerbs("Get")]
    public object Product(string name)
    {
       // return the Product with the given name...
    }
}

当我尝试api / Products / GetProducts /,它的作品. api /产品/产品?name = test也可以使用,但是api /产品/产品/测试不起作用.我究竟做错了什么?

更新:

以下是当我尝试api /产品/产品/测试时所得到的:

{
  "Message": "No HTTP resource was found that matches the request URI 'http://localhost:42676/api/Products/Product/test'.","MessageDetail": "No action was found on the controller 'Products' that matches the request."
}

解决方法

这是因为您的路由设置及其认值.你有两个选择.

1)通过更改路由设置以匹配Product()参数以匹配URI.

config.Routes.MapHttpRoute(
    name: "ActionApi",routeTemplate: "api/{controller}/{action}/{name}",// removed id and used name
    defaults: new { name = RouteParameter.Optional }
);

2)其他推荐的方法是使用正确的方法签名属性.

public object Product([FromUri(Name = "id")]string name){
       // return the Product with the given name
}

这是因为该方法在请求时期望参数idapi /产品/产品/测试,而不是寻找名称参数.

原文地址:https://www.jb51.cc/aspnet/246390.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐