1

我有一个接口和一个实现该接口的类

public interface ISessionVariables
{
    bool IsSessionTokenValidated { get; set; }
}

public class HttpContextSessionVariablesAdapter : ISessionVariables
{
    private T Get<T>(string key)
    {
        return (T)HttpContext.Current.Session[key];
    }

    private void Set(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public bool IsSessionTokenValidated
    {
        get { return Get<bool>("IsSessionTokenValidated"); }
        set { Set("IsSessionTokenValidated", value); }
    }
}

我使用 Ninject 将接口绑定到实现:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ISessionVariables>().To<HttpContextSessionVariablesAdapter>();
}

我有一个 ActionFilter

public class ValidateSessionTokenAttribute : ActionFilterAttribute
{
    [Inject]
    public ISessionVariables SessionVariables { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (SessionVariables.IsSessionTokenValidated == false)
        {
            throw new HttpException((int)HttpStatusCode.Unauthorized, "User session has expired");
        }

        base.OnActionExecuting(filterContext);
    }
}

奇怪的错误:

如果我将其添加ValidateSessionTokenAttribute到 ActionResult,则会SessionVariables填充属性。

[ValidateSessionToken]
public ActionResult Index()
{

}

如果我将相同的过滤器绑定到所有 ActionResults(在 FilterConfig 中),则该SessionVariables属性始终为null.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ValidateSessionTokenAttribute());
    }
}

我做错了什么?

4

0 回答 0