asp.net-mvc - 如何重载 MVC Controller 以避免重复公共(public)代码?

标签 asp.net-mvc overloading asp.net-mvc-5

我正在开发一个新的 MVC 5 项目。它是一个单一的 Multi-Tenancy 站点,允许许多组织和分支机构维护一个页面。所有页面都以以下 url 格式开头:

http://mysite.com/{organisation}/{branch}/...

例如:

http://mysite.com/contours/albany/...   
http://mysite.com/contours/birkenhead/...   
http://mysite.com/lifestyle/auckland/...   

我在 {controller}{action 之前用 {organisation}{branch} 声明了我的 RouteConfig :

routes.MapRoute(
    name: "Default",
    url: "{organisation}/{branch}/{controller}/{action}/{id}",
    defaults: new { controller = "TimeTable", 
                    action = "Index", 
                    id = UrlParameter.Optional });

这工作得很好。然而,现在每个 Controller 的顶部都有相同的代码,用于检查 organisationbranch

public ActionResult Index(string organisation, string branch, string name, int id)
{
    // ensure the organisation and branch are valid
    var branchInst = _branchRepository.GetBranchByUrlPath(organisation, branch);
    if (branchInst == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    // start the real code here...
}

我热衷于 DRY 原则(不要重复自己),我想知道是否有可能以某种方式隔离该公共(public)代码并将我的 Controller 签名更改为如下所示:

public ActionResult Index(Branch branch, string name, int id)
{
    // start the real code here...
}

最佳答案

您可以创建一个公共(public) Controller 并让您的其他 Controller 继承它。例如:

public class YourCommonController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var organisation = filterContext.RouteData.Values["organisation"];
            var branch = filterContext.RouteData.Values["branch"];

            // Your validation code here

            base.OnActionExecuting(filterContext);
        }
    }

现在,当您想要共享代码时,只需继承 YourCommonController

关于asp.net-mvc - 如何重载 MVC Controller 以避免重复公共(public)代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19149424/

相关文章:

azure - 无法将 Microsoft.Azure.Devices 添加到 ASP.NET 5 项目 : can't find fx/System.Net.Http.Formatting

javascript - 将列表中的项目循环到 Controller 中的 ViewBag 中

c# - VS Express 2013 RC for Web - 系统找不到指定的文件错误

c++ - C++ 中继承的重载规则

c++ - 使用 CRTP 继承

c# - 使用异步 Controller 的强类型 RedirectToAction( future )

asp.net-mvc - 使用 ASP.net MVC 项目作为其他 MVC 项目的 "base"项目

c# - 修改 API Controller 的路由以从 Controller 名称中删除 "API"

asp.net-mvc - 如何在网站上重新创建电子表格或共享点数据 TableView ?

c++ - 将 C++ 数学函数扩展到非基本类型