0

我正在尝试解决一个场景,我可以传入一个实体模型并检查它是否有一个 UserFK,如果它有,并且当前用户不是管理员角色.. 检查 UserFK 是否与当前用户的 UserId 匹配从数据库...

我只是无法用泛型解决最后一点..我认为我在正确的轨道上,但不太确定..

[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;
}

我不知道我是否以错误的方式思考它,或者是否有更好的方法,但我很想知道什么是可能的..

4

1 回答 1

0

为什么使用 Where 你可以使用 Find where Find 将搜索 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 
于 2012-08-22T11:54:45.130 回答