因此,我为WebAPI应用程序构建了一个概念验证原型,所有常用方法都很好。但我也想演示如何通过WebAPI调用自定义方法。所以,我在我的RouteConfig.cs以下路由:从WebAPI调用自定义方法
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
它的作品,即使方法本身不采取相提并论ameter。
所以在路由中,如果我将id设置为可选项,那么为什么当我不指定{id}时它不工作,但是如果我这样做了,那么即使方法本身不是'期待{id}?