如何在 ActionExecutingContext 中访问 Request.Properties

本文关键字:访问 Request Properties ActionExecutingContext | 更新日期: 2023-09-27 18:31:34

如何在ActionExecutingContext中访问Request.Properties

public class UserFilter : ActionFilterAttribute
{
    public void OnActionExecuting(ActionExecutingContext actionContext)
    {
        // Properties is not part of the Request here, so I can't access it
        // Here Request is of type System.Web.HttpRequestBase
        actionContext.HttpContext.Request.Properties.Add("UserData", new UserData());
    }
}

我可以在ApiController做到:

public class HomeController : ApiController
{
    public HomeController()
    {
        // Here I can do it (here Request is of type
        // System.Net.Http.HttpRequestMessage
        this.Request.Properties.Add("UserData", new UserData());
    }
}

如何在 ActionExecutingContext 中访问 Request.Properties

对于ApiController,您需要使用另一个ActionFilterAttribute(位于System.Web.Http.Controllers命名空间中):

    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    public class UserFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
                    // Properties is part of the Request here, you can access it
                    // actionContext.Request.Properties
        }
    }

actionContext.ActionDescriptor.Properties.Add("UserData", new UserData());