在我们新的非常大的MVC3应用程序中,我们有一个安全问题需要解决。我们的结构是每个控制器都有一个viewModel和一个viewModelGenerator类。 viewModelGenerator类负责根据需要从尽可能多的数据表构建viewModel。
我们的问题是每个用户仅限于查看其“办公室”的数据。因此,我们必须将用户“office”信息传递给每个viewModelGenerator。
有没有办法访问用户配置文件数据而不必将其作为参数从控制器传递?我可以通过构造函数传递值,但我们正在寻找一种更简洁的方法。我已经在SO上看过如何获得用户身份的帖子,但不是完整的个人资料。
答案 0 :(得分:2)
我们的结构是每个控制器都有一个viewModel
这是一个错误的结构。每个视图应该有一个视图模型,而不是每个控制器的视图模型。
是否有办法访问用户个人资料数据而无需通过 它作为控制器的参数?
否,不建议使用提取此类数据的服务层。必须将此数据从其所有者(即UI层)推送到服务层
在ASP.NET MVC中可以说有更多的MVCish方法来实现用户授权。一个示例是编写将在每个操作之前执行的自定义[Authorize]
属性,并验证用户是否有权访问该信息。
答案 1 :(得分:0)
我唯一的想法是创建一个共享父ViewModel,其中包含UserProfile作为公共字段。
因此,创建一个BaseViewModel并将每个ViewModel设置为从BaseViewModel继承。 ViewModelGenerator中唯一的变化应该是您需要在构造函数中为UserProfile设置适当的值。
我在这里使用public是为了便于使用,但如果它是一个安全问题可能会使用至少受保护的getter和setter。类似于:
public class ViewModel1 : BaseViewModel {
public ViewModel1 ()
:base(UserProfile profiledata){
//Constructor code for ViewModel1
}
}
并在BaseViewModel中:
public class BaseViewModel{
public UserProfile profile;
public BaseViewModel(UserProfile prof){
profile = prof;
}
}