DRY - 在MVC操作中停止重复获取,编辑和删除

时间:2012-07-24 15:10:12

标签: asp.net-mvc dry

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

2 个答案:

答案 0 :(得分:0)

使用action filters,在OnActionExecuting方法中进行验证。

答案 1 :(得分:0)

我最后继续使用我在原始问题中建议的方法。我确实考虑过使用@ SteveB的T4模板建议,但我发现T4模板有点难以使用。