そこで、WebAPI アプリの概念実証プロトタイプを作成しています。通常の方法はすべてうまく機能します。しかし、WebAPI を介してカスタム メソッドを呼び出すこともできることを示したかったのです。したがって、RouteConfig.cs には次のルーティングがあります。
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
コントローラーには、簡単な方法があります。
[HttpGet]
public string Test()
{
return "this is a string";
}
メソッドを呼び出そうとするとhttp://localhost:43225/api/values/test
、ブラウザに次のエラーが表示されます。
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'WebAPI_Listener.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</string>
しかし、URL の最後に ID を指定するとhttp://localhost:43225/api/values/test/1
、メソッド自体はパラメーターをまったく取りませんが、機能します。
したがって、ルーティングで id} をオプションとして設定している場合、{id} を指定しないと機能しないのはなぜですか。ただし、メソッド自体が { ID}??