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 /产品/产品/测试,而不是寻找名称参数.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....