次のルートに応答する ASP.NET Web API アプリケーションがあります。
1. http://localhost:1234/values
2. http://localhost:1234/values/123
3. http://localhost:1234/values/large
4. http://localhost:1234/values/small
注: これらのルートと例は単なる例です。しかし、それらは私が達成したいことに対応しています。
- 数値のリストなど、すべての値を返す必要があります。
- ID 123のリソースの値を返す必要があります。
- アプリが大きな値と見なすもののリストを返す必要があります。それが何であれ。
- アプリが小さな値と見なすもののリストを返す必要があります。
数十億の ASP.NET Web Api ルーティングの例と同様に、番号 (1) と (2) は簡単です。しかし、(3) と (4) を解決しようとすると、(1) と (2) は機能しなくなります。
これは私が現時点で持っているルートです:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// trying to map to "values/large" or "values/small"
routes.MapHttpRoute(
name: "ActionsApi",
routeTemplate: "{controller}/{action}",
defaults: null,
constraints: new { action = @"^[a-zA-Z]+$" }
);
// trying to map to "values/123"
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" }
);
// trying to map to "values"
routes.MapHttpRoute(
name: "ControllerApi",
routeTemplate: "{controller}"
);
上記のルートでは、(3) と (4) が機能します。
(2) リターン:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
No action was found on the controller 'Values' that matches the name '123'.
</string>
そして (1) を返します:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
Multiple actions were found that match the request:
System.Collections.Generic.IEnumerable`1[System.String] Get() on type MvcApplication3.Controllers.ValuesController
System.Collections.Generic.IEnumerable`1[System.String] Large() on type MvcApplication3.Controllers.ValuesController
System.Collections.Generic.IEnumerable`1[System.String] Small() on type MvcApplication3.Controllers.ValuesController
</string>
上記の 4 つの API の例をサポートするためにルートをセットアップする方法について、私は途方に暮れています。
編集: David のおかげで、彼は \w も数字と一致することを指摘したため、問題が発生しました。大小合わせて[a-zA-Z]+に変更しました。
(1)を除いてすべて動作するようになりました。
EDIT 2 @andrei が示唆したように、(1) を機能させるためにidパラメータをオプションにしましたが、そのルートで次のエラーが発生しました。
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
ここに追加したオプションのデフォルト:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^\d+$" }
);