[英]Controller Action Methods with different signatures
I am trying to get my URLs in files/id format. 我试图以文件/ id格式获取我的URL。 I am guessing I should have two Index methods in my controller, one with a parameter and one with not. 我猜我的控制器中应该有两个Index方法,一个带参数,一个带不带。 But I get this error message in browser below. 但我在下面的浏览器中收到此错误消息。
Anyway here is my controller methods: 无论如何这里是我的控制器方法:
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());
}
Update: Done with adding a route. 更新:完成添加路线。 Thanks to Jeff 谢谢Jeff
To use the files/id URL format, remove the parameterless Index
overload, and add this custom route first so it's evaluated before the default route: 要使用files / id URL格式,请删除无参数的Index
重载,并首先添加此自定义路由,以便在默认路由之前对其进行评估:
routes.MapRoute(
"Files",
"Files/{id}",
new { controller = "Files", action = "Index" }
);
See ASP.NET MVC Routing Overview for the basics of mapping URLs to controller methods and ScottGu's excellent URL Routing article, which has several examples very close to what you want to do. 有关将URL映射到控制器方法的基础知识以及ScottGu的优秀URL路由文章,请参阅ASP.NET MVC路由概述 ,该文章有几个非常接近您想要做的示例。
You can only overload Actions if they differ in arguments and in Verb, not just arguments. 如果它们在参数和动词中不同而不仅仅是参数,则只能重载Actions 。 In your case you'll want to have one action with a nullable ID parameter like so: 在您的情况下,您将希望有一个具有可空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 ");
}
}
You should also read Phil Haack's How a Method Becomes an Action . 您还应该阅读Phil Haack的“方法如何成为行动” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.