我正在使用MVC和代码优先实体框架(使用razor)学习ASP.NET。我一直在寻找关于这个主题的很多相互矛盾的信息,我想我会转向SO社区试图澄清一些事情。
从模型到控制器再到View,访问逻辑应该在哪里?例如(本文简化):
public class EmployeeController : Controller
{
private Repo _repo;
[HttpGet]
public ActionResult Create(int id)
{
Business business = _repo.FindBusiness(id);
if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
Employee employee = new Employee();
employee.Business = business;
return View();
}
}
[HttpPost]
public ActionResult Create(Employee employee)
{
Business business = _repo.FindBusiness(employee.business.ID);
if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
_repo.Save(employee);
Return Redirect(...);
}
}
}
然后我希望当前用户能够创建新业务,如果当前用户是业务的总经理或者他的父亲拥有该地点。我在这里要指出的是,它不依赖于用户的角色,而是依赖于一些业务逻辑来解释他们为何能够采取行动。
同样,我希望能够在相同条件的视图库中显示或隐藏链接,例如:
...
@if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
@Html.ActionLink(...)
}
...
我绝对不想这样做。我的问题是:如果访问逻辑可以捆绑为单个方法,那么该方法属于哪个"在mvc?它应该是ViewModel的只读属性吗?应该有一些静态访问控制器吗?模特本身的一部分?谢谢你的关注!
答案 0 :(得分:0)
您应该使用ActionFilters,请查看this示例。
请查看this答案以获得授权。
编写ActionFilter逻辑后,您的控制器将如下所示:
public class EmployeeController : Controller
{
private Repo _repo;
[CustomActionFilter] //your ACL logic will be here.
[HttpGet]
public ActionResult Create(int id)
{
//no acl logic in here.
}
[CustomActionFilter] //your ACL logic will be here.
[HttpPost]
public ActionResult Create(Employee employee)
{
//no acl logic in here.
}
}
ActionFilters也可以在Controller级别应用。