控制器操作具有不同签名的方法 [英] Controller Action Methods with different signatures

查看:268
本文介绍了控制器操作具有不同签名的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以 files / id 格式取得我的网址。我猜我应该有两个Index方法在我的控制器,一个有一个参数,一个没有。

I am trying to get my URLs in files/id format. I am guessing I should have two Index methods in my controller, one with a parameter and one with not. 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());
}

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

Update: Done with adding a route. Thanks to Jeff

推荐答案

您只能。在你的情况下,你会想要一个动作与一个可空的ID参数,如:

You can only overload Actions if they differ in arguments and in Verb, not just arguments. In your case you'll want to have one action with a nullable ID parameter like so:

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的方法如何成为行动

You should also read Phil Haack's How a Method Becomes an Action.

这篇关于控制器操作具有不同签名的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆