2012-08-22 27 views
0

我試圖玩弄這樣一個場景,我可以傳遞一個實體模型,並檢查是否有一個UserFK如果它與當前用戶不是在管理角色。 。檢查UserFK從DB當前用戶的用戶ID匹配...ASP.NET查詢泛型DBSet <T>

我不能與仿製藥制定出最後一位..我認爲正確的軌道上,但即時通訊也不太清楚..

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 
public class IsOwnerAttribute<T> : AuthorizeAttribute where T : class 
{ 
    public IsOwnerAttribute(IUnitOfWork context) 
    { 
     this.context = context; 
    } 

    public string RouteParameter 
    { 
     get { return this.routeParameter; } 
     set { this.routeParameter = value; } 
    } 

    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (filterContext == null) 
     { 
      throw new ArgumentNullException("filterContext"); 
     } 

     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      filterContext.Result = new HttpUnauthorizedResult(); 
     } 
     else if (IsOwner(filterContext)) 
     { 
      return; 
     } 
     else 
     { 
      ViewDataDictionary viewData = new ViewDataDictionary(); 
      viewData.Add("Message", "You do not have sufficient privileges for this operation."); 
      filterContext.Result = new ViewResult { ViewName = "Error", ViewData = viewData }; 
     } 

    } 

    bool IsOwner(AuthorizationContext filterContext) 
    { 
     bool result = false; 

     int id = -1; 
     if (filterContext.RouteData.Values.ContainsKey(this.RouteParameter)) 
     { 
      id = Convert.ToInt32(filterContext.RouteData.Values[this.RouteParameter]); 
     } 

     var currentUser = Membership.GetUser(); 
     if (currentUser != null && !filterContext.HttpContext.User.IsInRole("Administrator")) 
     { 
      var userGuid = (Guid)currentUser.ProviderUserKey; 

      // Stuck here.. trying to work out how with the Set<T> how i could then check if it has an Id property and a UserFK property and if it does then basically look up if the ID matches the ID in the route and the UserFK matches the userGuid then let them access the content... 
      result = context.Set<T>().Where(c => c.Id == id && c.UserFK == userGuid).SingleOrDefault() != null; 

     } 

     return result; 
    } 

    string routeParameter = "id"; 
    readonly IUnitOfWork context; 
    readonly IDbSet<T> dbset; 
} 

我不知道如果我想這是錯誤的方式,或者如果有更好的方式做它,但很想知道什麼是可能的..

+0

這樣做有什麼目的? –

+0

你的屬性確實太多了。阻止將任何邏輯實現爲屬性(尤其是使您可以與數據庫通信的事物)。此外,屬性不能是泛型類型。 – Steven

回答

0

爲什麼使用哪裏可以使用查找哪裏查找將搜索T主鍵並使用對象作爲參數。我認爲這會解決你的問題。

例如更改此:

result = context.Set<T>().Where(c => c.Id == id && c.UserFK == userGuid).SingleOrDefault() != null; 

與此

result = context.Set<T>().Find(id);//and you don't need to filter also with user if your ID is primary key of the table