繁体   English   中英

懒 <T> 真的很懒

[英]Lazy<T> really is lazy

我在Lazy<T>上遇到问题,我无法解决问题所在。

我正在返回cookie的内容,但是如果我使用Lazy<T> ,则需要花费2秒钟来验证用户身份。 我有一些可以在第一次使用的简单代码,但是正如我所说,我无法弄清为什么Lazy<T>方法不能按预期工作。

这是2个摘要-没有其他区别。

片段1-正常工作

public FormsAuthenticationTicket Ticket
{
    get
    {
        var ck = Helper.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (ck != null)
        {
            return FormsAuthentication.Decrypt(ck.Value);
        }
        return null;
    }
}

片段2-需要按两次该按钮

Lazy<HttpCookie> lazyCookie = new Lazy<HttpCookie>(GetCookie);

public FormsAuthenticationTicket Ticket
{
    get
    {
        if (Cookie != null  &&  !string.IsNullOrEmpty(Cookie.Value))
        {
            return FormsAuthentication.Decrypt(Cookie.Value);
        }
        return null;
    }
}

HttpCookie Cookie
{
    get { return lazyCookie.Value; }
}

static HttpCookie GetCookie()
{
    return Helper.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
}

从httpmodule ::完全相同的方式调用这两段代码:

    public void Init(HttpApplication context)
    {
        context.PostAuthenticateRequest += PostAuthenticateRequest;
    }

    void PostAuthenticateRequest(object sender, EventArgs e)
    {
        var page = Helper.Context.Handler as Page;
        if (page != null)
        {
            StoreUserDetails();
        }
    }

    void StoreUserDetails()
    {
        var ticket = new FormsAuthCookie().Ticket;
        if (ticket != null)
        {
            var identity = new UserIdentity(ticket);
            var roles = Roles.GetRolesForUser(identity.Name);
            var principle = new GenericPrincipal(identity, roles);

            Helper.Context.Current.User = principle;
        }
    }

如果基于基本用户信息登录,我将重定向用户:

            if(User.IsInRole("SuperAdmin"))
                Response.RedirectToRoute("PageAdmin");

使用Lazy代码,我必须登录两次才能看到结果,第一个代码段是第一次运行。

编码,

public FormsAuthenticationTicket Ticket
{
    get
    {
        return new Lazy<FormsAuthenticationTicket>(() =>
            {
                var ck =
                    Helper.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (ck != null)
                {
                    return FormsAuthentication.Decrypt(ck.Value);
                }

                return null;
            }).Value;
    }
}

是您的Snippet 1代码的直接Lazy等效项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM