Multiple Controller Types with same Route prefix ASP.NET Web Api

前端 未结 3 1411
旧巷少年郎
旧巷少年郎 2020-11-29 05:06

Is it possible to separate GETs and POSTs into separate API Controller types and accessing them using the same Route Prefix?

Here are my controllers:



        
3条回答
  •  孤城傲影
    2020-11-29 05:48

    Take advantage of partial classes. Partial Classes and Methods - C# MSDN

    Create two files: BooksController.Write.cs and BooksController.Read.cs Only RoutePrefix one file, since they are the same class it will give you an error saying you are prefixing the same class two times.

    Both files will compile as a single class (because it is a single class, but split in different files).

    // File BooksController.Write.cs
    [RoutePrefix("api/Books")]
    public partial class BooksController : EventStoreApiController
    {
        [Route("")]
        public void Post([FromBody] CommandWrapper commandWrapper){...}
    }
    
    // File BooksController.Read.cs
    public partial class BooksController : MongoDbApiController
    {
        [Route("")]
        public Book[] Get() {...}
    
    
        [Route("{id:int}")]
        public Book Get(int id) {...}
    }
    

提交回复
热议问题