我们能重载 MVC 控制器动作方法吗?(MVC 多态性)





4.00/5 (10投票s)
在本文中,我们将学习是否可以重载 MVC 控制器动作方法。
上周六和周日,我在孟买参加 MVC 课程时,一位参与者提出了一个奇怪的问题:我们能重载 MVC 动作方法吗?这个问题最近在他参加 MVC 面试时被问到。
当时我感到奇怪,面试官会问这种不能测试程序员能力的问题。但让我们把这个争论留到以后再说,先来回答这个问题吧。
答案是“是”和“否”,这取决于你的期望。在你们把我当成一个两面派政客之前,让我解释一下为什么我会给出这种模棱两可的答案。
重载或换句话说,多态性是面向对象编程的特性。所以,如果你有如下控制器代码,其中方法使用相同的名称和不同的参数被重载,它将能够很好地编译。
public class CustomerController : Controller
{
//
// GET: /Customer/
publicActionResultLoadCustomer()
{
return Content("LoadCustomer");
}
publicActionResultLoadCustomer(string str)
{
return Content("LoadCustomer with a string");
}
}
但是,如果你认为当你调用“https://:3450/Customer/LoadCustomer/”时,它应该调用“LoadCustomer”,而当你调用“https://:3450/Customer/LoadCustomer/test”时,它应该调用“LoadCustomer(string str)”,你就错了。
如果你尝试这样做,你将会遇到下面的错误。仔细阅读错误中的“Ambiguous”(歧义)一词,有没有什么想法?好的,让我更详细地解释一下这个错误的意思。
多态性是 C# 编程的一部分,而 HTTP 是一种协议。HTTP 不理解多态性,它基于 URL 的概念运作,而 URL 只能拥有唯一的名称。因此,HTTP 不实现多态性。
我知道如果你用上面的论点回答,MVC 面试官仍然会坚持他想实现多态性,那么我们该如何实现呢?
如果你希望保留多态性,并且希望 HTTP 请求能够工作,你可以使用“ActionName”装饰其中一个方法,如以下代码所示。
public class CustomerController : Controller
{
//
// GET: /Customer/
publicActionResultLoadCustomer()
{
return Content("LoadCustomer");
}
[ActionName("LoadCustomerbyName")]
publicActionResultLoadCustomer(string str)
{
return Content("LoadCustomer with a string");
}
}
现在,你可以使用 URL 结构“Customer/LoadCustomer”调用“LoadCustomer”动作,使用 URL 结构“Customer/LoadCustomerByName”调用“LoadCustomer(string str)”。
如需进一步阅读,请观看以下面试准备视频和分步视频系列。