我正在尝试以 files / id 格式获取我的网址。我猜我的控制器中应该有两个Index方法,一个带参数,一个带不带。但是我在下面的浏览器中收到此错误消息。
无论如何,这是我的控制器方法:
public ActionResult Index()
{
return Content("Index ");
}
public ActionResult Index(int id)
{
File file = fileRepository.GetFile(id);
if (file == null) return Content("Not Found");
else return Content(file.FileID.ToString());
}
更新:完成添加路线。感谢Jeff
答案 0 :(得分:5)
要使用 files / id 网址格式,请删除无参数Index
重载,并首先添加此自定义路由,以便在默认路由之前对其进行评估:
routes.MapRoute(
"Files",
"Files/{id}",
new { controller = "Files", action = "Index" }
);
有关将URL映射到控制器方法的基础知识以及ScottGu的优秀ASP.NET MVC Routing Overview文章,请参阅URL Routing,该文章有几个非常接近您想要做的示例。
答案 1 :(得分:4)
如果参数和动词不同,你只能overload Actions,而不仅仅是参数。在您的情况下,您将希望有一个具有可空ID参数的操作,如下所示:
public ActionResult Index(int? id){
if( id.HasValue ){
File file = fileRepository.GetFile(id.Value);
if (file == null) return Content("Not Found");
return Content(file.FileID.ToString());
} else {
return Content("Index ");
}
}
您还应该阅读Phil Haack的How a Method Becomes an Action。