每个用户的站点范围变量 [英] site wide variables per user

查看:166
本文介绍了每个用户的站点范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC4站点,需要在用户登录时(并且只在用户登录时)维护一些信息。例如,一旦用户登录,我就收到一个'用户令牌',允许我访问几个关闭现场服务。

我尝试了两种不同的方法。首先是使用访问用户会话的公共静态类。但是,在阅读静态类之后,我犹豫使用它们。根据我正在阅读的内容,静态类只能用于只读对象,而我并没有这样使用它。尽管该网站似乎在数量有限的用户中工作正常(目前有10个)。



(如果有人想向我解释为什么在MVC4中这是一个坏主意,请告诉我和/或链接到一篇文章)。
$ b

  public class SessionAccessorClasses 
{
public const string SessionAccessorSessionVariablesString =_SessionAccessorSessionVariables;
public static SessionAccessorModel SessionVariables
{
get {return System.Web.HttpContext.Current.Session!= null? (SessionAccessorModel)System.Web.HttpContext.Current.Session [SessionAccessorSessionVariablesString]:null; }
set {System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString,value); }
}
}

我的第二个(当前)方法是使用会话变量并使用全局可用的类访问它们。

  public class SessionAccessorClasses 
{
private const string SessionAccessorSessionVariablesString =_SessionAccessorSessionVariables;
public SessionAccessorModel GetSessionVariables()
{
return System.Web.HttpContext.Current.Session!= null? (SessionAccessorModel)System.Web.HttpContext.Current.Session [SessionAccessorSessionVariablesString]:null;
}
public void SetSessionVariables(SessionAccessorModel value)
{
System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString,value);

public void ClearSessionVariables()
{
System.Web.HttpContext.Current.Session.Remove(SessionAccessorSessionVariablesString);


$ / code $ / pre
$ b $ p

这很好,但我不愿称它为好是因为我不完全理解为什么公共静态类是一个糟糕的主意,并且因为我现在必须在几乎每个函数的开始都实例化我的新类,并在每个函数结束时调用Set / Update函数;某种程度上感觉错了。

因此,首先,由于我的原始静态类访问用户会话,这真的很糟吗?第二,是我的第二堂课更合适的做事方式吗?你可以提出改进建议吗?

第三,如果没有别的办法,你可以给我这样做的积极/消极方面吗?

解决方案

您想使用 Session in ASP.net 。它是为您描述的目的而创建的。


ASP.NET会话状态使您能够在用户导航时为用户存储和检索值Web应用程序中的ASP.NET页面。 HTTP是一种无状态协议。这意味着Web服务器将每个HTTP请求作为独立请求处理。服务器不知道以前请求期间使用的变量值。 ASP.NET会话状态会在有限的时间窗口内将来自同一浏览器的请求标识为会话,并提供一种在该会话持续时间内保留变量值的方法。默认情况下,为所有ASP.NET应用程序启用ASP.NET会话状态。


我喜欢强类型可重用会话变量,所以我写了下面的扩展来存储你想创建的任何变量,而不需要经常记住魔术字符串

  public static class SessionExtensions 
{
public static bool TryGetValue< ; T>(此HttpSessionStateBase会话,输出T值)
其中T:class
{
var name = typeof(T).FullName;

value = session [name] as T;

var result = value!= null;

返回结果;


public static void SetValue< T>(this HttpSessionStateBase session,T value)
{
var name = typeof(T).FullName;

session [name] = value;


public static void RemoveValue< T>(this HttpSessionStateBase session)
{
var name = typeof(T).FullName;

session [name] = null;


public static bool ValueExists(this HttpSessionStateBase session,Type objectType)
{
var name = objectType.FullName;

var result = session [name]!= null;

返回结果;




$ b $ p $所以如果你有一个类:

  public MyClass 
{
public int MyInt {get;组; }
}

您可以通过以下方式进行存储:

  Session.SetValue(MyClass); 




需要维护一些信息while(and only only while)用户已登录。


可以通过几种方法更新这些方法来满足此要求。这里有一种方法:

pre $ lt; code> public static bool TryGetAuthenticatedValue< T>(这个HttpSessionStateBase会话,
out T值)
其中T:class
{
value = null; $(HttpContext.Current.User!= null
&&&& HttpContext.Current.User.Identity!= null
&&& HttpContext.Current.User。 IsAuthenticated)
{
var name = typeof(T).FullName;

value = session [name] as T;
}

var result = value!= null;

返回结果;
}

我还建议您存储在会话中的任何类都可以序列化。也就是说它有一个无参数的构造函数,标记为 [Serializable]

I have an MVC4 site that needs to maintain some information while (and ONLY while) the user is logged in. For example, once the user logs in, I get a 'user token' back that allows me access to several off site services.

I've tried two different approaches. The first was to use a public static class that accesses the user session. However, after reading up on static classes, I'm hesitant to use them. According to what I'm reading, static classes should only be used for read only objects, and I wasn't using it that way. Although the site site did seem to be working fine with a limited number of users (currently there's 10).

(If someone would like to explain to me why this is a bad idea in MVC4, please tell me and/or link to an article)

public class SessionAccessorClasses
{
    public const string SessionAccessorSessionVariablesString = "_SessionAccessorSessionVariables";
    public static SessionAccessorModel SessionVariables
    {
        get { return System.Web.HttpContext.Current.Session != null ? (SessionAccessorModel)System.Web.HttpContext.Current.Session[SessionAccessorSessionVariablesString] : null; }
        set { System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString, value); }
    }
}

My second (and current) approach is to use Session variables and access them using a globally available class.

public class SessionAccessorClasses
{
    private const string SessionAccessorSessionVariablesString = "_SessionAccessorSessionVariables";
    public SessionAccessorModel GetSessionVariables()
    {
        return System.Web.HttpContext.Current.Session != null ? (SessionAccessorModel)System.Web.HttpContext.Current.Session[SessionAccessorSessionVariablesString] : null;
    }
    public void SetSessionVariables(SessionAccessorModel value)
    {
        System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString, value);
    }
    public void ClearSessionVariables()
    {
        System.Web.HttpContext.Current.Session.Remove(SessionAccessorSessionVariablesString);
    }
}

This works fine, but I hesitate to call it good is because I don't fully understand why the public static class was such a bad idea, and because I now have to instantiate my new class at the beginning of nearly every function, and call the Set/Update function at the end of every function; which feels wrong somehow.

So first, since my original static class was accessing the users session, is it really that bad?

Second, is my second class a more appropriate way of doing things? Can you suggest improvements?

Third, if nothing else, can you give me the positive/negative aspects of doing it either way?

解决方案

You want to use Session in ASP.net. It was created for the purpose you describe.

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

I'm a fan of strongly-typed reusable session variables, so I wrote the following extensions to store whatever variables you want to create without the need to constantly remember magic strings.

public static class SessionExtensions
{
    public static bool TryGetValue<T>(this HttpSessionStateBase session, out T value) 
      where T : class
    {
        var name = typeof(T).FullName;

        value = session[name] as T;

        var result = value != null;

        return result;
    }

    public static void SetValue<T>(this HttpSessionStateBase session, T value)
    {
        var name = typeof(T).FullName;

        session[name] = value;
    }

    public static void RemoveValue<T>(this HttpSessionStateBase session)
    {
        var name = typeof(T).FullName;

        session[name] = null;
    }

    public static bool ValueExists(this HttpSessionStateBase session, Type objectType)
    {
        var name = objectType.FullName;

        var result = session[name] != null;

        return result;
    }
}

So if you have a class:

public MyClass
{
  public int MyInt { get; set; }
}

You can store it by simply:

Session.SetValue(MyClass);

that needs to maintain some information while (and ONLY while) the user is logged in.

These methods could be updated a few ways to fulfill this requirement. Here is one way:

public static bool TryGetAuthenticatedValue<T>(this HttpSessionStateBase session, 
  out T value) 
  where T : class
{
    value = null;

    if (HttpContext.Current.User != null
        && HttpContext.Current.User.Identity != null
        && HttpContext.Current.User.IsAuthenticated)
    {
      var name = typeof(T).FullName;

      value = session[name] as T;
    }

    var result = value != null;

    return result;
}       

I would also recommend that whatever classes you store in session, be serializable. That is to say it has a parameterless constructor and marked as [Serializable].

这篇关于每个用户的站点范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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