从 httpcontext 访问 viewcontext

Access viewcontext from httpcontext

我想从 httpcontext 获取 ViewData 值。 我的函数:

[LogActionFilter]
public ActionResult Edit(int id = 0)
{
    var obj = getObjFromDb(id);
    ViewData["abc"] = obj.name;
    return View(obj);
}

我要访问的操作过滤器 ViewData 值:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var a= filterContext.HttpContext.Items["abc"]; //null
        var b = filterContext.HttpContext.Request.RequestContext.HttpContext.Items["abc"]; //null
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var a= filterContext.HttpContext.Items["abc"]; //null
        var b = filterContext.HttpContext.Request.RequestContext.HttpContext.Items["abc"]; //null
    }
}

如何从 HttpContext 访问 ViewData 的值?

您可以使用会话将值传递到您的 OnActionExecuted 过滤器中。但是,您不能将操作中的任何内容传递给 OnActionExecution,因为它在您的操作之前执行。

 [LogActionFilter]
  public ActionResult Edit(int id = 0)
  {
    var obj = getObjFromDb(id);
    Session["abc"] = obj.name;
    return View(obj);
  }

在过滤器中:

public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var a = filterContext.HttpContext.Session["abc"];
        /// a should have a value
    }

感谢 Stephen Muecke,

ViewData is not available in HttpContext

所以我改变了我的逻辑,而不是获取 viewdata 值,我在操作过滤器中从数据库中获取数据。