【问题标题】:ASP.Net Core WebApi - storing values from ActionFilter to access in controllerASP.Net Core WebApi - 存储 ActionFilter 中的值以在控制器中访问
【发布时间】:2020-05-21 14:50:53
【问题描述】:

在 ASP.Net Core WebApp 中,我想使用 ActionFilter 并将信息从 ActionFilter 发送到应用它的控制器。

MVC

对于 MVC,我可以做到这一点

动作过滤器

    public class TenantActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //Using some sneaky logic to determine current tenant from domain, not important for this example
            int tenantId = 1;
            Controller controller = (Controller)context.Controller;
            controller.ViewData["TenantId"] = tenantId;
        }
        public void OnActionExecuted(ActionExecutedContext context) { }
    }

控制器

    public class TestController : Controller
    {
        [ServiceFilter(typeof(TenantActionFilter))]
        public IActionResult Index()
        {
            int tenantId = ViewData["TenantId"];
            return View(tenantId);
        }
    }

它可以工作,我可以通过 ViewData 将数据传回控制器 - 很棒。

WebApi

我想为 WebApi 控制器做同样的事情。

actionFilter 本身可以应用、运行等 - 但我无法写入 ViewData,因为 WebAPI 继承自 ControllerBase - 而不是来自 Controller(如 MVC)。

问题

如何将数据从我的 ActionFilter 推送回调用 ControllerBase,类似于 MVC?

注意事项

  • 正在使用 ASP.Net Core 2.2,但如果解决方案不能在所有 .Net Core 中使用,我会感到惊讶。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-webapi


    【解决方案1】:

    ...所以当我几乎写完问题时我找到了答案,所以这里...

    答案是 HttpContext.Items 集合

    动作过滤器

        public class TenantActionFilter : IActionFilter
        {
            public void OnActionExecuting(ActionExecutingContext context)
            {
                int tenantId = 1;
                var controller = (ControllerBase)context.Controller;
                controller.HttpContext.Items.Add("TenantId", tenantId);
            }
            public void OnActionExecuted(ActionExecutedContext context) { }
        }
    

    控制器

        public class TestApiController : ControllerBase
        {
            [ServiceFilter(typeof(TenantActionFilter))]
            public SomeClass Get()
            {
                int tenantId;
                if (!int.TryParse(HttpContext.Items["TenantId"].ToString(), out tenantId))
                {
                    tenantId = -1;
                }
                return new SomeClass();
            }
        }
    

    【讨论】:

    • 保持状态似乎与无状态控制器的概念不一致。
    • 对于多租户应用程序,我需要确定调用的方法与哪个域相关联。我可以直接在 actionmethod 中执行此操作,但将其封装在可重用的 actionfilter 中似乎更干净——至少对我而言。
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2022-12-29
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多