1

由于我创建了一个具有多个 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 方法?

4

2 回答 2

2

您可以为您的第一条路由添加一个约束,以便它只匹配 {id} 参数的数字:

config.Routes.MapHttpRoute(
    name: "ActionById",
    routeTemplate: "api/Search/{action}/{id}",
    defaults: new { controller = "Search", id = RouteParameter.Optional },
    constraints: new { id = @"\d+" }
);

或者,您可以完全删除您的第二条路线,并将您的操作签名更改为仅使用 {id} 参数:

[HttpGet]
public IEnumerable<Object> CompanyByOrderId(long id) { ... }
[HttpGet]
public IEnumerable<Object> CompanyByName(string id) { ... }
[HttpGet]
public IEnumerable<Object> UserByName(string id) { ... }
于 2013-10-08T10:53:19.807 回答
2

你能对这些路线进行硬编码吗?如果是这样,类似的东西应该可以工作。

config.Routes.MapHttpRoute(
    name: "CompanyByNameRoute",
    routeTemplate: "api/Search/CompanyByName/{name},
    defaults: new { controller = "Search", action = "CompanyByName", name = RouteParameter.Optional }
    );
于 2013-10-01T12:12:25.330 回答