2017-05-19 9 views
2

Web APIを初めて使用しています。私はそれが動詞に基づいていると思ったので、私は論理も同様に望んでいたと思いました。Web API同じパラメータで2つのメソッドを定義する方法

削除と取得のためのAPIを作成したい場合は、同じ署名が付いています。

[HttpGet] 
public HttpResponseMessage Index(int id) 
{ 
    return Request.CreateResponse(HttpStatusCode.OK, GetValue()); 
} 

[HttpDelete] 
public HttpResponseMessage Index(int id) 
{ 
    //logic 
    return Request.CreateResponse(HttpStatusCode.OK, true); 
} 

私は、別の動詞Web Api 2が指定することを望んでいました。しかし、私が更新した場合でも、私はまだ同じパラメータ型がすでに存在しているとのメンバーと呼ばれる指標としてオフ聞いています(注意ボイド戻り値の型)

[HttpDelete] 
public void Index(int id) 
{ 
    //logic 
} 

に削除します。

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-clientによると、それは、GET、PUTと同じURLを持つ削除

Action    HTTP method Relative URI 
Get a product by ID  GET   /api/products/id 
Create a new product  POST   /api/products 
Update a product   PUT   /api/products/id 
Delete a product   DELETE   /api/products/id 

を示しています。悲しいことに、彼らはクライアント側のサーバサイドコードを表示しません。

はへの私の唯一のオプションは次のとおりです。

1. Overload the method (in this example, seems like it would be hacking as it's not needed to perform the required task) 
2. Give the method a different name (eg `Delete` instead of `Index`) 

それとも別の方法はありますか?

答えて

1

あなたは構文の問題を持っています。属性ルートを使用して同じパスを維持できますが、メソッドの名前と構造が異なるか、既に経験したようなコンパイルエラーが発生します。

あなたの質問から例を使用して

Action     HTTP method Relative URI 
Get a product by ID  GET   /api/products/id 
Create a new product  POST   /api/products 
Update a product   PUT   /api/products/id 
Delete a product   DELETE   /api/products/id 

上記

[RoutePrefix("api/products")] 
public class ProductsController : ApiController { 

    [HttpGet] 
    [Route("{id:int}")] //Matches GET api/products/1 
    public IHttpActionResult Get(int id) { 
     return Ok(GetValueById(id)); 
    } 

    [HttpPost] 
    [Route("")] //Matches POST api/products 
    public IHttpActionResult Post([FromBody]Product model) { 
     //...code removed for brevity 
    } 

    [HttpPut] 
    [Route("{id:int}")] //Matches PUT api/products/1 
    public IHttpActionResult Put(int id, [FromBody]Product model) { 
     //...code removed for brevity 
    } 

    [HttpDelete] 
    [Route("{id:int}")] //Matches DELETE api/products/1 
    public IHttpActionResult Post(int id) { 
     //...code removed for brevity 
    } 
} 
に一致するコントローラとなり、次の
1

あなたは以下を確認して、APIメソッドにルート属性を使用することができます。

[HttpGet] 
    [Route("same")] 
    public IHttpActionResult get(int id) 
    { 
     return Ok(); 
    } 

    [HttpDelete] 
    [Route("same")] 
    public IHttpActionResult delete(int id) 
    { 
     return Ok(); 
    } 

とPOST/PUTのために同様のGET要求を取得し、削除要求のために削除するHTTPメソッドを設定します。

enter image description here

enter image description here

enter image description here

enter image description here

関連する問題