asp.net-web-api2 - 如何在 AuthenticationFilter 之后、Action 之前在 ApiController 中运行代码?

标签 asp.net-web-api2

我正在尝试实现 IAuthenticationFilter( Web Api 2 风格,而不是 MVC 风格)并且我正在努力处理代码的执行顺序。我本来希望身份验证过滤器在任何基于 Controller 的东西之前运行,这样我就可以设置适当的主体,然后在某种基本 ApiController 中从我的 DbContext 加载相关的用户数据。

这是我追求的流程:

AuthenticationFilter ==> BaseController ==> Controller/Action
  • 身份验证过滤器:- 如果一切顺利,测试授权 header 并设置主体。
  • 基本 Controller :- 使用主体在数据库中查找完整的用户记录并将其分配给 protected属性(property)。
  • Controller / Action :- 正常完成操作,可以访问
    在 BaseController 中设置的用户记录。

  • 我不确定将代码放在 BaseController 的何处以便在身份验证过滤器之后但在解析的 Controller /操作之前执行它。

    问题

    所以我的问题是双重的:我是否以错误的方式解决这个问题?如果没有,我应该如何执行第 2 步?

    最佳答案

    这就是我最终做的。在我的 BaseController 中,我创建了一个名为 LoggedInUser 的 protected 属性,并创建了一个特殊的 getter:

    private User _loggedInUser;
    protected User LoggedInUser
    {
        get
        {
            if (_loggedInUser != null) return _loggedInUser;
    
            var identity = RequestContext.Principal.Identity;
            var userId = identity.GetUserId();
    
            _loggedInUser = MyDbContext.Users.Find(userId);
            return _loggedInUser;
        }
    }
    

    这允许我将代码保存在一个地方,即 BaseController,同时仍然允许我将获取用户的尝试推迟到身份验证发生之后。

    关于asp.net-web-api2 - 如何在 AuthenticationFilter 之后、Action 之前在 ApiController 中运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289144/

    相关文章:

    owin - 如何生成不记名 token 来调用远程 Web API

    c# - Web API中多个过滤器的执行顺序

    mysql - Web API 没有得到正确的结果

    asp.net-mvc - Web API 帮助页面未加载文档 XML

    asp.net-web-api2 - 使用 Swashbuckle 的性能影响

    c# - 在同一 Controller 上的 Web Api 中多次 POST 调用的最佳实践

    c# - 使用Windows身份验证的Asp.net核心Web API - Cors请求未经授权

    c# - session 或 webAPI 中的任何替代方案

    c# - 将json数据反序列化为c#中的列表

    rest - 南希 : How to mimic Web API plain NotFound response?