我正在尝试解决一个场景,我可以传入一个实体模型并检查它是否有一个 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;
}
我不知道我是否以错误的方式思考它,或者是否有更好的方法,但我很想知道什么是可能的..