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

2024-01-05

我正在尝试获取我的网址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());
}

更新:添加路线完成。感谢杰夫


你只能过载动作 https://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc如果它们在参数和动词上不同,而不仅仅是参数不同。在您的情况下,您需要一个带有可为空 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 的方法如何变成行动 http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有不同签名的控制器操作方法 的相关文章

随机推荐