假设我有一个 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# 不支持预处理器宏或类似的东西,因为这是使用它们的好地方。除非有更好的方法?