Asp.net core ASP.Net核心WebApi-将ActionFilter中的值存储到控制器中的访问
在ASP.Net核心WebApp中,我希望使用ActionFilter并将信息从ActionFilter发送到应用它的控制器 MVC 对于MVC,我可以做到这一点 动作过滤器 控制器 它可以工作,我可以通过ViewData将数据传回控制器-太好了 WebApi 我想对WebApi控制器也这样做 actionFilter本身可以应用、运行等,但我无法写入ViewData,因为WebAPI继承自ControllerBase,而不是Controller(如MVC) 问题: 我如何将数据从ActionFilter推送到调用的ControllerBase,类似于MVC 笔记Asp.net core ASP.Net核心WebApi-将ActionFilter中的值存储到控制器中的访问,asp.net-core,asp.net-core-mvc,asp.net-core-webapi,Asp.net Core,Asp.net Core Mvc,Asp.net Core Webapi,在ASP.Net核心WebApp中,我希望使用ActionFilter并将信息从ActionFilter发送到应用它的控制器 MVC 对于MVC,我可以做到这一点 动作过滤器 控制器 它可以工作,我可以通过ViewData将数据传回控制器-太好了 WebApi 我想对WebApi控制器也这样做 actionFilter本身可以应用、运行等,但我无法写入ViewData,因为WebAPI继承自ControllerBase,而不是Controller(如MVC) 问题: 我如何将数据从ActionF
- 正在使用ASP.NETCore2.2,但如果一个解决方案不能在所有.NETCore中使用,我会感到惊讶
保持状态似乎与无状态控制器的概念不一致。对于多租户应用程序,我需要确定调用的方法与哪个域相关联。我可以直接在actionmethod中这样做,但将其包装在可重用的actionfilter中似乎要干净得多——至少对我来说是这样。
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);
}
}
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();
}
}