WebApi添加另一个Get方法

Kyl*_*bel 3 c# get asp.net-web-api

我有一个非常标准的WebApi,可以执行一些基本的CRUD操作.

我正在尝试添加一些不同类型的查找,但我不太确定它是如何完成的.

这是我目前的FoldersController

public class FoldersController : ApiBaseController
{
    //using ninject to pass the unit of work in
    public FoldersController(IApiUnitOfWork uow)
    {
        Uow = uow;
    }

    // GET api/folders
    [HttpGet]
    public IEnumerable<Folder> Get()
    {
        return Uow.Folders.GetAll();
    }

    // GET api/folders/5
    public Folder Get(int id)
    {
        return Uow.Folders.GetById(id);
    }

    // POST api/folders
    public HttpResponseMessage Post(Folder folder)
    {
        Uow.Folders.Add(folder);
        Uow.Commit();

        var response = Request.CreateResponse(HttpStatusCode.Created, folder);

        // Compose location header that tells how to get this Folder
        response.Headers.Location = new Uri(Url.Link(WebApiConfig.DefaultRoute, new { id = folder.Id }));

        return response;
    }

    // PUT api/folders
    public HttpResponseMessage Put(Folder folder)
    {
        Uow.Folders.Update(folder);
        Uow.Commit();
        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

    // DELETE api/folders/5
    public HttpResponseMessage Delete(int id)
    {
        Uow.Folders.Delete(id);
        Uow.Commit();

        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是添加一个看起来像这样的方法

public IEnumerable<Folder> GetChildFolders(int folderID)
{
     return Uow.Folders.GetChildren(folderID);
}
Run Code Online (Sandbox Code Playgroud)

由于我已经有了标准的Get方法,我不太清楚如何这样做.

我最初以为我可以添加一条新路线......就像

routes.MapHttpRoute(
        name: "ActionAndIdRoute",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: null,
        constraints: new { id = @"^/d+$" } //only numbers for id
        );
Run Code Online (Sandbox Code Playgroud)

只需在我的方法中添加类似ActionName注释的内容即可 [ActionName("GetChildren")]

但那并没有飞.

我是在正确的轨道上吗?如何在不添加其他控制器的情况下执行此类操作?

Chr*_*xon 11

你可能不喜欢这个答案,但我觉得这是正确的答案.WebAPI被设计为每个实体类型只有5个调用,GET(一个项目/列表项),POST,PUT和DELETE.这允许REST URL,例如Folders/Get/5,Folders/Get等.

现在,在您的场景中,您想要ChildFolders,我可以理解它们不是不同的对象,但它们在REST(ChildFolders/Get)等方面是不同的实体.我觉得这应该是另一个WebAPI控制器.

有一些方法可以修补Http路由来管理这个,但是我觉得Web API的设计并不是这样的,它强制你遵循REST数据逐个实体类型的协议......否则为什么不使用用于AJAX调用的.NET MVC控制器?