41

Actionメソッドのパラメータータイプベースのオーバーロードを実行する方法はありますか?すなわち、コントローラーで次のことを行うことは可能ですか?

public class MyController : ApiController
{
   public Foo Get(int id) { //whatever }

   public Foo Get(string id) { //whatever }

   public Foo Get(Guid id)  { //whatever }
}

その場合、ルートテーブルにどのような変更を加える必要がありますか。

4

2 に答える 2

35

この種のシナリオは、標準のルーティング方法では十分にサポートされていません。

代わりに属性ベースのルーティングを使用することをお勧めします。これにより、柔軟性が大幅に向上します。

具体的には、次のタイプでルーティングできるルート制約を確認してください。

// Type constraints
[GET("Int/{x:int}")]
[GET("Guid/{x:guid}")]

それ以外のものは少しハックになります...例えば

標準のルーティングを使用して試行した場合は、その名前を使用して正しいアクションにルーティングする必要があります。次に、正規表現の制約(guidなど)を使用して、必要なデフォルトのアクションにルーティングします。

コントローラー:

public class MyController : ApiController
{
   [ActionName("GetById")]
   public Foo Get(int id) { //whatever }

   [ActionName("GetByString")]
   public Foo Get(string id) { //whatever }

   [ActionName("GetByGUID")]
   public Foo Get(Guid id)  { //whatever }
}

ルート:

        //Should match /api/My/1
        config.Routes.MapHttpRoute(
            name: "DefaultDigitApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { action = "GetById" },
            constraints: new { id = @"^\d+$" } // id must be digits
        );

        //Should match /api/My/3ead6bea-4a0a-42ae-a009-853e2243cfa3
        config.Routes.MapHttpRoute(
            name: "DefaultGuidApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { action = "GetByGUID" },
            constraints: new { id = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" } // id must be guid
        );

        //Should match /api/My/everything else
        config.Routes.MapHttpRoute(
            name: "DefaultStringApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { action = "GetByString" }
        );

更新しました

FromBodyを実行する場合は通常POSTを使用します(おそらく、代わりにモデルでFromUriを使用します)が、以下を追加することで要件を満たすことができます。

コントローラ用

    [ActionName("GetAll")]
    public string Get([FromBody]MyFooSearch model)
    {
         if (model != null)
        {
            //search criteria at api/my
        }
        //default for api/my
    }

    //should match /api/my
    config.Routes.MapHttpRoute(
                name: "DefaultCollection",
                routeTemplate: "api/{controller}",
                defaults: new { action = "GetAll" }
            );
于 2013-01-16T12:36:48.817 に答える
7

以下のようにメソッドをコーディングできます

    [Route("api/My/{id:int}")]
    public string Get(int id)
    {
        return "value";
    }

    [Route("api/My/{name:alpha}")]
    public string Get(string name)
    {
        return name;
    }

    [Route("api/My/{id:Guid}")]
    public string Get(Guid id)
    {
        return "value";
    }
于 2016-07-14T08:58:32.067 に答える