Web API 1 | .NET 4.5.2。 |使用 http 动词而不是动作进行路由,无需外部库

问题描述 投票:0回答:0

我在 MSDN、SO 和其他网站上的任何地方都找不到此信息,而且我已经搜索了好几天。 我在一个 WEB API 1 - .NET 4.5.2 项目上,我需要公开一个 CRUD 控制器。 这意味着我不能在 WebApi2 中使用一些强大的属性,比如:

  • [Route("...")]
  • [RoutePrefix("...")]
  • ...

我需要我的 api 来使用这个表格:

prot://url:port/api/mycontroller/{tablename}/{id}

其中 {tablename} 已经是要使用的参数,id si 可选。

使用 Postman,比方说,我想要:

  • 我执行
    Get(string tablename)
    时要调用的动作
    GET | prot://url:port/api/mycontroller/{tablename}
  • 我执行
    Post(string tablename)
    时要调用的动作
    POST | prot://url:port/api/mycontroller/{tablename}
  • 等等 我希望这个行为专门针对这个特定的控制器。
public class SpecificController : ApiController { 
    [HttpGet]
    public object Get(string tablename, string id) { . . . }
    [HttpPost]
    public object Post(string tablename) { . . . }

    . . .
 }

我在我的 WebApiConfig.Register 类方法上添加了一个新路由:

config.Routes.MapHttpRoute(
  name: "SpecificApi",
  routeTemplate: "api/{controller}/{table}/{id}",
  constraints: new { controller = "/^specific$" },
  defaults: new { id = RouteParameter.Optional }
);

我构建、启动,它看起来很好。 但是,当通过 Postman 执行调用时,我收到以下错误消息

any verb | http://localhost:port/api/specific/mytable

"Message":"No HTTP resource was found that matches the request URI 'http://localhost:port/api/specific/mytable'."
"MessageDetail": "No action was found on the controller 'Specific' that matches the name 'mytable'."

如果我使用默认路由,它工作正常,这意味着在控制器名称后添加动作

(Get(), Post(), ...)
...

我不明白,为什么它只匹配动作而不匹配动词? 此外,我不应该使用其他第三方库,除了那些由微软提供的。

提前致谢

c# asp.net-web-api webapi asp.net-web-api-routing
© www.soinside.com 2019 - 2024. All rights reserved.