この種のシナリオは、標準のルーティング方法では十分にサポートされていません。
代わりに属性ベースのルーティングを使用することをお勧めします。これにより、柔軟性が大幅に向上します。
具体的には、次のタイプでルーティングできるルート制約を確認してください。
// 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" }
);