繁体   English   中英

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

[英]Controller Action Methods with different signatures

我试图以文件/ 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());
}

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

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

routes.MapRoute(
        "Files",
        "Files/{id}",
        new { controller = "Files", action = "Index" }      
    );

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

如果它们在参数和动词中不同而不仅仅是参数,则只能重载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的“方法如何成为行动”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM