在asp.net请求级单对象 [英] a request level singleton object in asp.net

查看:99
本文介绍了在asp.net请求级单对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一种伪单身的实施。我希望它的工作方式类似于的HttpContext 没有工作,在那里我可以得到一个实例的情况下做的简单的东西:

I trying to write a kind of pseudo singleton implementation. I want it to work similar to how HttpContext does work, where I can get an instance to the context doing something as simple as:

var ctx = HttpContext.Current;

所以我的实现是这样的:

So my implementation goes something like this:

public class AppUser
{
    public string Username { get; set; }
    public string[] Roles { get; set; }

    public AppUser()
    {
        var appuser = HttpContext.Session["AppUser"] as AppUser;
        if(appuser == null)
            throw new Exception("User session has expired");
        Username = appuser.Username;
        Roles = appuser.Roles;
    }
}


public class WebAppContext
{
    const string ContextKey = "WebAppContext";

    WebAppContext() { } //empty constructor
    public static WebAppContext Current 
    {
        get
        {
            var ctx = HttpContext.Current.Items[ContextKey] as WebAppContext;
            if(ctx == null)
            {
                try
                {
                    ctx = new WebAppContext() { User = new AppUser() };
                }
                catch
                {
                    //Redirect for login
                }
                HttpContext.Current.Items.Add(ContextKey, ctx);                     
            }       
            return ctx;     
        }
    }

    public AppUser User { get; set; }
}

和我尝试使用这个对象如下:

And I try to consume this object as follows:

var appuser = WebAppContext.Current.User;

现在做上述额度担保,我得到了正确的请求上下文相关联的用户;未被处理它与其他并发的HTTP请求相关的一些其他用户?

Now does the above line guarantee I get the user associated with the correct request context; not some other user which is associated with another concurrent http request being processed?

推荐答案

除了事实,我不明白为什么你需要勉强将用户信息从会话容器的答案复制到项目的容器,你问题应该是 - 是的,如果会话数据正确,那么同样的数据将可从您的静态属性。

Apart from the fact that I can't understand why would you need to barely copy the user information from the Session container to the Items container, the answer to your question should be - yes, if the Session data is correct then the same data will be available from your static property.

我写上博客条目一次

http://netpl.blogspot.com/2010/ 12 /容器基础的pseudosingletons-in.html

这篇关于在asp.net请求级单对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆