加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net Web Api路由不工作

发布时间:2020-12-15 19:40:35 所属栏目:asp.Net 来源:网络整理
导读:这是我的路由配置: config.Routes.MapHttpRoute( name: "ActionApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }); 而且,这是我的控制器: public class ProductsController : ApiController{ [Accep
这是我的路由配置:
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 /产品/产品/测试,而不是寻找名称参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读