2016-08-07 5 views
1

目的:REST動詞名を定義し、それらをREST経路にリンクしたいと思います。私はOwinStartup.csに持​​ってC#Web Api Routing

GET/=> Get() 
GET /1 => Get(int id) 
POST/=> Post() 
PUT/=> Put() 
DELETE /1 => Delete(int id) 
GET /custom => [HttpGet][ActionName("custom")] GetCustom() 

httpConfiguration.Routes.MapHttpRoute (
    name: "ControllerWithId", 
    routeTemplate: "rest/{controller}/{id}", 
    constraints: new { 
     id = @"^\d+$" 
    }, 
    defaults: new { 
     action = "Index", 
     id = RouteParameter.Optional 
}); 
httpConfiguration.Routes.MapHttpRoute (
    name: "ControllerWithAction", 
    routeTemplate: "rest/{controller}/{action}/{id}", 
    defaults: new { 
     action = "Index", 
     id = RouteParameter.Optional 
    }); 

私はApiController持っている:

public class MyController : ApiController { 
    public async Task<IEnumerable<object>> Get() {} 
    public async Task<object> Get(int id) {} 
    public async Task Post([FromBody] data) {} 
    public async Task Put(int id, [FromBody] data) {} 
    public async Task Delete(int id) {} 
    [HttpGet][ActionName("custom")] 
    public async Task Custom() {} 
} 

彼らはすべてのリターンを次に、私が定義されたアクション名にカスタムルールをマップしたいです404カスタムを除いて。各RESTメソッドにActionNameを追加する必要があります。最も簡潔なソリューションは何ですか?

+0

?そして、 'Task' *の代わりに' IHttpActionResult'の実装を返すべきです。* –

+0

私はそれを考えましたが、デフォルトの命名規則を使用したいと思っていました。 – Exegesis

+0

@Exegesis以下の投稿があなたのために働いた場合、他の人がそれを好むように答えとして受け入れるべきです –

答えて

0

ASP.NET MVCは、CRUD /カスタムエンドポイントのための彼らの名前の規則を使用して簡単な方法を提供していません。私は醜いルートに行き、各CRUDメソッドに対して明示的にActionName("")を指定しました。

reyan-chougleのソリューションでは、コード内の文字列をハードコードする必要がありますが、これは悪い習慣です。属性に魔法の文字列を追加しようとしましたが、コンパイルエラーが発生しました。

ソリューション:あなたがルーティング属性を使用していないのはなぜ

[HttpGet] 
    [ActionName (Consts.defaultActionMethdName)] 
    public IEnumerable<Model> Get() {} 

    [HttpGet] 
    [ActionName (Consts.defaultActionMethdName)] 
    public Model Get (int id) {} 

    [ActionName (Consts.defaultActionMethdName)] 
    public IHttpActionResult Post ([FromBody] Model input) {} 

    [ActionName (Consts.defaultActionMethdName)] 
    public IHttpActionResult Put (int id, [FromBody] Model input) {} 

    [ActionName (Consts.defaultActionMethdName)] 
    public IHttpActionResult Delete (int id) {} 

    [HttpGet] 
    [ActionName("custom")] 
    public async Task Custom() {}