C# mvc中调用动作方法的模糊性

C# mvc中调用动作方法的模糊性,c#,asp.net-mvc,routing,C#,Asp.net Mvc,Routing,我正在创建一个示例mvc应用程序,并在主控制器中创建了两个操作方法(索引) public class HomeController : Controller { // // GET: /Home/ public string Index() { return Index1(); } public string Index(string message) { return "hello";

我正在创建一个示例mvc应用程序,并在主控制器中创建了两个操作方法(索引)

public class HomeController : Controller
{
    //
    // GET: /Home/        
    public string Index()
    {
        return Index1();
    }

    public string Index(string message)
    {
        return "hello";
    }
}
并且索引被设置为运行应用程序时的默认操作。在运行应用程序时,我得到以下错误:

控制器类型上操作“索引”的当前请求 “HomeController”在以下操作方法之间不明确: 类型上的System.String索引(Int32) Mvc4example.Controllers.HomeController System.String Mvc4example.Controllers.HomeController类型上的索引(System.String)

我所期望的是,如果没有查询字符串,它将调用无参数的操作方法,如果传递了查询字符串消息,那么将调用带有参数的操作方法


有人能解释为什么会有这种行为吗?

你有第三种类似的行为

    public string Index(int id)
    {
            return "int";       
    }
这可以解释这种行为


当然,您也不需要无参数操作,这只是message one的一个特例,其中message为空

如果您有两个名称相同的方法,Http请求属性必须不同

public class HomeController : Controller
{
    [HttpGet]        
    public string Index()
    {
        //...
    }

    [HttpPost]
    public string Index(string message)
    {
        //...
    }
}

请检查这篇文章中的答案:更多细节,但要总结一下:

上最多只能有两个同名的操作方法 一个控制器,为了做到这一点,必须是[HttpPost],并且 其他必须是[HttpGet]

因为两个方法都是GET,所以应该重命名其中一个 操作方法或将其移动到其他控制器


这是MVC的工作方式,在选择方法时不考虑参数。如果您想要这种行为,您需要自己调整它,例如使用查看查询字符串和方法参数的
ActionMethodSelectorAttribute
。不,我没有那种操作方法,但是我仍然会得到同样的错误,即使在添加了你提到的动作方法之后。你不需要两个实际上相同的动作,因为其他人也已经正确回答了,例如@Max Brodin