【发布时间】:2014-03-01 07:14:42
【问题描述】:
有点 asp.net mvc noob ,我正在尝试传入一个字符串作为我的 Web API 控制器的参数:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
public string Get(string arg)
{
return "othervalue";
}
}
我尝试添加另一条路线:
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{arg}",
defaults: new { controller = "Home", action = "Index", arg = UrlParameter.Optional }
);
所以我想保留两个 Get 方法并使用带 arg 参数的 Get,这样我就可以传入一个字符串。因此,当我尝试在浏览器中点击此 url 'api/values/jjhjh' 时,我收到此错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'stackOverflowWebApi.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
【问题讨论】:
-
你能说明你是如何尝试传递字符串的吗?
-
你试过让 id 可以为空吗?
-
您显示的路线是
Routeconfig,您能告诉我们您的WebApiconfig -
你的自定义路由是放在
RouteConfig中的默认路由之前还是之后? -
为什么你有第二个默认路由和第一个默认路由做同样的事情?那不会做任何事情。我建议使用路由调试器对您必须查看的路由进行故障排除,看看它失败的原因。请参阅 Phil Hackk 关于 Route 调试器的博客。
标签: asp.net asp.net-mvc-4 c#-4.0 asp.net-mvc-routing