0

私はという名前のコントローラーを持っています

Products と i には 3 つのアクションがあります

  • Product : int を受け取り、モデル (クラス) オブジェクトを返します
  • カテゴリ:文字列を受け取り、モデル (クラス) オブジェクトの配列を返します
  • すべて:モデル (クラス) オブジェクトの配列を返すパラメーターはありません

私が試していたのは、次のマッピングでした

製品-> api / 製品 / 製品 / 1

カテゴリ-> api / 製品 / カテゴリ / ソース

すべて-> api / 製品 / すべて

アクションの名前はURL構造をサポートしているので、一般的なルートを試していました

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

他のすべては機能していますが、このhttp://localhost:2271/api/products/category/2URLを使用すると次のエラーが発生します

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:2271/api/products/category/2'.
</Message>
<MessageDetail>
No action was found on the controller 'Products' that matches the request.
</MessageDetail>
</Error>

一方、この URL api/products/category/?cat=abc&api/products/category?cat=abcは正常に機能しています...... [cat は受信パラメータ名です]

ヘルプ !!!

4

1 に答える 1

1

一方、この URL api/products/category/?cat=abc & api/products/category?cat=abc は正常に動作しています

そうです、そうなります。それが RPC スタイルのやり方です。RESTful な方法を維持したい場合は、次のルート構成を使用できます。

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

config.Routes.MapHttpRoute(
    name: "ProductByCategory",
    routeTemplate: "api/{controller}/category/{cat}"
);

config.Routes.MapHttpRoute(
    name: "DefaultByAction",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { action = "Get" }
);

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

コントローラーは次のようになります。

public class ProductsController : ApiController
{
    // api/products/
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };            
    }

    // api/products/5
    [HttpGet]
    public string Get(int id)
    {
        return "Product" + id;
    }

    // api/products/category/fruits
    [HttpGet]
    public string Category(string cat)
    {
        return "Product " + cat;
    }    
}

注: 簡単にするために文字列を返しましたが、 a のインスタンスを返すと想定しておりProduct、そのようにコードを簡単に変更できます。

于 2013-04-09T05:28:32.420 に答える