由于我创建了一个具有多个 get 方法的单独搜索控制器,因此我需要修改默认路由。
搜索控制器.cs
[HttpGet]
public IEnumerable<Object> CompanyByOrderId(long id) { ... }
[HttpGet]
public IEnumerable<Object> CompanyByName(string name) { ... }
[HttpGet]
public IEnumerable<Object> UserByName(string name) { ... }
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionById",
routeTemplate: "api/Search/{action}/{id}",
defaults: new { controller = "Search", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionByName",
routeTemplate: "api/Search/{action}/{name}",
defaults: new { controller = "Search", name = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
参考http://localhost:52498/api/Search/CompanyByOrderId/1
工作正常。但是使用名称作为参数调用其他方法之一会导致 404 错误。例如http://localhost:52498/api/Search/UserByName/john
如何指定带有字符串参数的 URI 映射到 CompanyByName / UserByName 方法?