在 API 控制器中调用自定义方法

Calling custom methods in API controller

我在我的网络 api 控制器中添加了一个方法:

public String GetpeopleInFamily(string familyId)

我遵循了这个问题的一些例子: Custom method names in ASP.NET Web API

我根据上面阅读的内容更新了我的 RouteConfig.cs 文件: public static void RegisterRoutes(RouteCollection 路由) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        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":"No HTTP resource was found that matches the request URI 'http://localhost:17438/api/people/GetpeopleInFamily/101 '.","MessageDetail":"No action was found on the controller 'people' that matches the request."}

我需要做什么才能让它发挥作用?此外,添加 return 更复杂数据集的自定义方法是否是最佳实践?

familyId 没有映射到路由中。因此,您可以创建一个新的映射,将 familyId 添加到 id 映射或将 GetPeopleInFamily 的参数重写为 id.

重写:

public string GetPeopleInFamily(string id)

创建新路线:当您创建新路线时,请务必删除带有 id 的映射,否则将无法使用。

routes.MapHttpRoute("DefaultApiWithActionAndFamilyId", "Api/{controller}/{action}/{familyId}", new { familyId = RouteParameter.Optional }, new { familyId = @"\d+" });

您需要配置 Web API 路由以接受 familyId 参数。

config.Routes.MapHttpRoute(name: "newont",
                routeTemplate: "api/{controller}/{familyId}/{id}",
                defaults: new { controller = "Controllername", familyId= "familyId", new { id = RouteParameter.Optional }}
            );