具有不同签名的控制器操作方法

Ufu*_*arı 4 c# model-view-controller asp.net-mvc controller asp.net-mvc-routing

我试图以文件/ id格式获取我的URL .我猜我的控制器中应该有两个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());
}
Run Code Online (Sandbox Code Playgroud)

更新:完成添加路线.谢谢Jeff

R0M*_*RMY 5

如果动作在参数和动词上不同,而不仅仅是参数,则只能重载它们。在您的情况下,您需要一个带有可为空 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 ");
    }
}
Run Code Online (Sandbox Code Playgroud)

您还应该阅读 Phil Haack 的《方法如何成为行动》


Jef*_*nal 5

要使用files/id URL格式,请删除无参数Index重载,并首先添加此自定义路由,以便在默认路由之前对其进行评估:

routes.MapRoute(
        "Files",
        "Files/{id}",
        new { controller = "Files", action = "Index" }      
    );
Run Code Online (Sandbox Code Playgroud)

有关将URL映射到控制器方法的基础知识以及ScottGu的优秀URL路由文章,请参阅ASP.NET MVC路由概述,该文章有几个非常接近您想要做的示例.