2011-08-08 38 views
2
public ActionResult Index(int ehrId, int? page) 
{ 
    EHR ehr = ehrRepository.FindById(ehrId); 
    if (ehr.UserName != User.Identity.Name) 
     return View("Invalid Owner"); 

    var physicaltests = ehr.PhysicalTests.Where(test=>!test.IsDeleted).OrderByDescending(test => test.CreationDate); 
    List<PhysicalTestListItem> physicalTestsVM = new List<PhysicalTestListItem>(); 
    Mapper.Map(physicaltests, physicalTestsVM); 
    var paginatedTests = physicalTestsVM.ToPagedList(page ?? 0, PAGESIZE);// new PaginatedList<PhysicalTestListItem>(physicalTestsVM, page ?? 0, pageSize); 
    return View(paginatedTests); 
} 

public ActionResult Create(int ehrId) 
{ 
    EHR ehr = ehrRepository.FindById(ehrId); 
    if (ehr.UserName != User.Identity.Name) 
     return View("Invalid Owner"); 

    return View(new PhysicalTestForm()); 
} 

我的PhysicalTestsController執行前執行了這三行代碼,絕對是我所有的方法。我如何重構這個以避免這麼多的重複?我只包括了兩種方法,但實際上有六種方法。此代碼是否適合ActionFilter?

回答

1

我想是這樣的

的行爲過濾器將是適當的驗證輸入數據。

EHR ehr = ehrRepository.FindById(ehrId); 
if (ehr.UserName != User.Identity.Name) 
    return View("Invalid Owner"); 

將是適當的放在一個行爲過濾器,我創建了其它輸入驗證在[需要登錄]或[RequiresSSL]在過去這麼多個動作可以共享相同的代碼(onBeforeExcuting或onAfterExecuted)。

看點的橫切面向對象編程參與討論

但是其他的東西,如日誌記錄是在你的架構的所有層的橫切關注點,你可能想看看AOP(面向方面​​編程)幫助避免在那裏重複代碼。

更新 - 示例代碼(未經測試)

public class CheckValidUserAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     IMyRepository myRepository = IoC.Resolve<IMyRepository>(); 
     Int64 userId;  
     if(Int64.TryParse(filterContext.HttpContext.Request.QueryString["id"]), out userId)) 
     if(!IsValidUser(userId)) 
      filterContext.Result = new InvalidUserResult(); 
    } 

    public bool IsValidUser(IMyRepository myRepository, Int64 userId) 
    { 
     EHR ehr = ehrRepository.FindById(ehrId);  
     return ehr != null && ehr.UserName == User.Identity.Name; 
    } 
} 

喜歡的東西上面應該這樣做,你需要創建一個名爲視圖來回報您「無效用戶「,但這應該是微不足道的。網絡上應該有很多關於如何創建和使用動作過濾器的例子。我個人從臨ASP.NET MVC框架和

+0

學到的是需要反射來獲取ehrId如果您使用的行爲過濾器? – BZink

+0

@BZink - 沒有反射不需要TMK,但是增加了複雜性,您必須從ActionExecutedContext或ActionExecutingContext中檢索值來檢索動作參數(在本例中爲ehrId)。 –

+0

感謝您的非常完整的答案..我一定要儘可能多地學習...你會介意分享一些代碼,以便我有一個想法,我可以使這個actionFilter的工作?..是沒關係的參考資料庫裏面的actionfilter ?.在此先感謝 – ignaciofuentes