我这个看到的问题是, 这将是应用广泛,
然后,你需要处理它普遍的服务。令人惊讶的是,我将其称为IAuthorisationService。
和我 正在寻找有关如何处理此问题的最佳实践。我应该在CustomControllers看 ?过滤器?或者 是什么?
无论您选择哪种方式,都应该使用上面的常见IAuthorisationService。
从我的经验,我可以告诉大家,它更容易注入服务到控制器,并使用它的每一个动作:
/* Interfaces */
public interface IAuthorisationService {
bool CanEdit(YourItem item);
}
public interface ICurrentUserProvider {
YourUserEntity GetCurrentUser();
}
/* Implementations */
public class HttpUserProvider : ICurrentUserProvider {
public YourUserEntity GetCurrentUser() {
return HttpContext.Current.User.Principal as YourUserEntity;
}
}
public calss RolesAuthorisationService : IAuthorisationService {
ICurrentUserProvider userProvider
public RolesAuthorisationService(ICurrentUserProvider userProvider) {
this.userProvider = userProvider;
}
public bool CanEdit(YourItem item) {
var u = userProvider.GetCurrentUser();
if (u == null)
return false;
return item.Owner == u && u.IsInRole("EditYourItem");
}
}
/* Controller */
public class MyController: Controller {
IAuthorisationService authorisation;
public MyController(IAuthorisationService authorisation) {
this.authorisation = authorisation;
}
public ActionResult Edit(int id) {
var item = GetTheItembyIdSomehow();
if (!authorisation.CanEdit(item))
return new HttpUnauthorizedResult();
// Can do this
}
}
然后你可以使用的ControllerFactory自动注入所需的依赖到控制器:
class DependencyInjectionContainer : WindsorContainer {
public DependencyInjectionContainer() {
RegisterDependencies();
}
private void RegisterDependencies() {
// Services
Register(
AllTypes.Of<IDiscoverableService>()
.FromAssembly(typeof(IDiscoverableService).Assembly)
.Configure(c => c.LifeStyle.Transient)
.WithService.FromInterface()
);
// Controllers
Register(
AllTypes.Of<IController>()
.FromAssembly(typeof(DependencyInjectionContainer).Assembly)
.Configure(c => c.LifeStyle.Transient)
);
}
}
class WindsorControllerFactory : DefaultControllerFactory, IDisposable {
private readonly IWindsorContainer container;
public WindsorControllerFactory() {
container = new DependencyInjectionContainer();
}
protected override IController GetControllerInstance(Type controllerType) {
if (controllerType == null)
return base.GetControllerInstance(controllerType);
return (IController) container.Resolve(controllerType);
}
public void Dispose() {
container.Dispose();
}
}
好的建议。 Re:权限表,ContentID是什么?可以说我有Orders,OrderItems,SalesSlips等......很多实体。 contentId是什么?我怎么知道那个ID地图呢? – zzz 2009-11-26 00:49:27
在这种情况下,您需要另一个属于TableID的权限表中的字段。有一个包含表名和表ID的表也很好。 – 2009-11-26 01:52:14
或者,您可以移动到用户有权访问的实体,该实体包含有问题的记录。例如,如果销售人员可以访问特定的订单,他还可以访问该订单上的所有订单项。 – 2009-11-26 02:00:44