【发布时间】:2012-07-24 15:10:12
【问题描述】:
假设我有一个 CategoriesController 来管理某种类别列表。它有这些动作方法:
public ActionResult Get(Int32 categoryId);
public ActionResult Edit(Int32 categoryId);
[HttpPost]
public ActionResult Edit(Int32 categoryId, CategoryModel model);
public ActionResult Delete(Int32 categoryId);
[HttpPost]
public ActionResult Delete(Int32 categoryId, DeleteModel model);
所有这些方法都运行相同的代码来验证categoryId 是否有效并且类别存在,它从数据库中检索它,并执行访问级别验证。部分验证码直接返回ActionResult,其他则不返回(例如categoryId不存在,则立即返回Http404动作结果,但如果一切正常则归结为特定动作代码。
是减少代码重复的最佳方法吗?
private ActionResult EnsureCategory(Int32 categoryId, out DBCategory dbCategory);
public ActionResult Edit(Int32 categoryId) {
DBCategory dbCategory;
ActionResult error = EnsureCategory(categoryId, out dbCategory);
if( error != null ) return error;
// this now means that only 3 lines of code will be shared between the Action methods, but it still seems too much.
}
很遗憾 C# 不支持预处理器宏或类似的东西,因为这是使用它们的好地方。除非有更好的方法?
【问题讨论】:
-
预处理器宏可以替换为 T4 模板。这甚至可以远远超出简单的预处理器
标签: asp.net-mvc dry