如何在ActionExecutingContext中访问Request.Properties

时间:2014-11-22 18:35:29

标签: c# asp.net-mvc asp.net-web-api

如何访问Request.Properties中的ActionExecutingContext

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());
    }
}

2 个答案:

答案 0 :(得分:1)

对于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
        }
    }

答案 1 :(得分:-1)

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