使用不同参数的重载操作

时间:2016-01-05 10:50:19

标签: c# asp.net-mvc asp.net-mvc-5

我有几个从公共基础继承的模型类(例如Class1Class2继承自CommonClass)。我想编写单独的重载控制器动作,它将每个模型类作为参数。例如:

    [HttpPost]
    public JsonResult MyAction(Class1 data)
    {
       // handle data here
    }

    [HttpPost]
    public JsonResult MyAction(Class2 data)
    {
       // handle data here
    }

是否有可能实现这一目标?当我尝试简单地编写这些动作方法时,MVC会抛出System.Reflection.AmbiguousMatchException

我还尝试用基类作为参数编写单个动作,然后将数据转换为特定的类,但这给了我null

    [HttpPost]
    public JsonResult MyAction(CommonClass data)
    {
        if(data.IsSomething)
        {
            var castedData = data as Class1;
            // process casted data
        }
        else
        {
            var castedData = data as Class2;
            // process casted data
        }
    }

2 个答案:

答案 0 :(得分:3)

在同一个控制器上不能有多个具有相同名称和HTTP谓词的操作。您需要具有不同的动作名称和路线。

另外,您可以结帐this answer,其中我将说明如何编写自定义模型绑定器并实现多态绑定(您对基类的第二次尝试)。

答案 1 :(得分:1)

您可以使用[ActionName]注释修饰您的操作。像这样:

[HttpPost, ActionName("OtherName")]
public JsonResult MyAction(Class1 data)
{
   // handle data here
}

[HttpPost]
public JsonResult MyAction(Class2 data)
{
   // handle data here
}

通过这种方式,您可以使用包含.NET不允许的字符的名称,例如[ActionName("This-Example")]

相关问题