我在web api控制器中添加了一个方法:
public String GetpeopleInFamily(string familyId)
我从这个问题中得到了一些例子: Custom method names in ASP.NET Web API
我根据上面的内容更新了我的RouteConfig.cs文件: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute(" {资源}个.axd / {*} PATHINFO&#34);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiWithActionAndId", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint("Get") });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint("Post") });
}
但是在调用方法时我仍然得到404:
请求GET / api / people / GetpeopleInFamily / 101 HTTP / 1.1
{" Message":"未找到与请求URI匹配的HTTP资源 ' http://localhost:17438/api/people/GetpeopleInFamily/101 '。"," MessageDetail":"未在控制器'人员' 与请求匹配。"}
我需要做些什么才能让它发挥作用?同样,这是添加返回更复杂数据集的自定义方法的最佳做法吗?
答案 0 :(得分:1)
familyId
未映射到路线中。因此,您可以创建一个新的Mapping,它将familyId添加到id映射或将GetPeopleInFamily
的参数重写为id
。
重写:
public string GetPeopleInFamily(string id)
创建新路线:创建新路线时,请确保使用id
删除映射,否则将无效。
routes.MapHttpRoute("DefaultApiWithActionAndFamilyId", "Api/{controller}/{action}/{familyId}", new { familyId = RouteParameter.Optional }, new { familyId = @"\d+" });
答案 1 :(得分:1)
您需要配置您的Web API路由以接受familyId参数。
config.Routes.MapHttpRoute(name: "newont",
routeTemplate: "api/{controller}/{familyId}/{id}",
defaults: new { controller = "Controllername", familyId= "familyId", new { id = RouteParameter.Optional }}
);