c# - 在 MVC 应用程序的存储库层中进行授权的模式

标签 c# .net asp.net-mvc asp.net-mvc-4 repository-pattern

我有一个经过 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/

相关文章:

c# - 如何引发 MouseClick 事件?

c# - 在 asp.net 中使用隐藏代码在页面加载时显示弹出 div?

c# - 将音频(字节数组)发布到 MVC.NET Web Api

c# - 处理 TypedDataset 中的 Null

c# - 获取和处理 MVC 中输入的数据 - 简单

c# - 使用 PIC16F877 (MikroC IDE) 从 c# 接口(interface)接收 3 位数字

.net - 为什么我应该使用 WPF 而不是 Winforms? WPF 优于 Winforms 的任何示例?

c# - 保存 Outlook 约会后的事件

asp.net-mvc - CustomErrors web.config 设置和 azure 应用洞察日志记录之间有什么关系?

c# - 使用带有 Entity Framework 的动态字段按子记录排序