我正在开发一个新的 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 的顶部都有相同的代码,用于检查 organisation
和 branch
。
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/