asp.net mvc 4-WEBAPI ActionContext Request.Properties.Add用于存



我想将操作过滤器(数据库)中的信息传递给action函数。

使用ActionContext Request.Properties.Add存储数据是否安全?

WEBAPI客户端或其保险箱是否有可能看到这些信息,因为在Cache\Session中存储信息是安全的?

这是更好的方法吗?

除非显式序列化请求属性,否则客户端不会看到它们。它们完全保留在服务器端。

为了回答你的后续问题,这里有另外两种方法。没有"最佳"方法本身。这完全取决于你希望信息流到什么程度,以及你希望过滤器有多通用。我个人喜欢使用控制器对象,但这只是一种偏好。

对于示例,这里有一个简单的值控制器和一个POCO类:

[MyActionfilter]
public class ValuesController : ApiController
{
    public string Foo { get; set; }
    public User Get(User user)
    {
        if (Foo != null && user != null)
        {
            user.FamilyName = Foo;
        }
        return user;
    }
}

public class User
{
    public string FirstName { get; set; }
    public string FamilyName { get; set; }
}

下面的动作过滤器天真地实现了对控制器对象或方法参数的访问。请注意,您可以谨慎地应用过滤器,也可以进行类型检查/字典检查。

public class MyActionfilter : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        controller = actionContext.ControllerContext.Controller;
        // Not safe unless applied only to controllers deriving
        // from ValuesController
        ((ValuesController)controller).Foo = "From filter";
        // Not safe unless you know the user is on the signature
        // of the action method.
        actionContext.ActionArguments["user"] = new User()
        {
            FirstName = "From filter"
        };
    }
}

相关内容

最新更新