我有一个经过 Windows 身份验证的带有存储库层的 MVC 应用程序。 Controller 与数据库的所有交互都是通过存储库完成的。每个 Controller 都有一个对存储库的引用:
public class PostController : Controller
{
private Repository db = new Repository();
[HttpPost]
public ActionResult DeletePost(int id)
{
// Authorize that the user is allowed to delete this post...
db.DeletePost(id);
}
}
我的问题是是否有一种好的方法可以将我的授权逻辑移至存储库层。我希望 Repository.DeletePost()
函数拒绝删除不是由经过身份验证的用户创建的帖子。问题是我的存储库不知道经过身份验证的用户是谁。 Controller 知道(通过 Controller.User
)。
将 Controller.User
传递到 Repository
构造函数中不起作用,因为 Controller.User
当时显然没有定义当调用构造函数时。
我如何通知Repository
谁是经过身份验证的用户?最好只在每个操作中构造 Repository
吗?还是在存储库层处理它是个坏主意?
最佳答案
Or is it a bad idea to handle it in the repository layer?
我认为 Controller 是您授权的更好地方。让存储库成为数据的网关,让 Controller 成为您应用程序的看门人。我希望尽可能早地在生命周期中看到授权/身份验证逻辑。
关于c# - 在 MVC 应用程序的存储库层中进行授权的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14901540/