문제

대신

 session("myvar1") = something
 session("myvar2") = something
 session("myvar3") = something
 session("myvar4") = something

enum sessionVar
   myvar1
   myvar2
   myvar3
   myvar4
end enum


 session(sessionVar.myvar1.tostring) = something
 session(sessionVar.myvar2.tostring) = something
 session(sessionVar.myvar3.tostring) = something
 session(sessionVar.myvar4.tostring) = something

더 나은 것?

도움이 되었습니까?

해결책

대신 사용하여 상수에 대한 세션 키,나를 사용하여 내 자신의 유형-안전한 세션 객체에는 다음과 같습니다(이에서는 C#,아래를 참조하십시오 VB 버전):

public class MySession
{
  // Private constructor (use MySession.Current to access the current instance).
  private MySession() {}

  // Gets the current session.
  public static MySession Current
  {
    get
    {
      MySession session = HttpContext.Current.Session["__MySession__"] as MySession;
      if (session == null)
      {
        session = new MySession();
        HttpContext.Current.Session["__MySession__"] = session;
      }
      return session;
    }
  }

  // My session data goes here:
  public string MyString { get; set; };
  public bool MyFlag { get; set; };
  public int MyNumber { get; set; };
}

해야 할 때마다 나는 읽기/쓰기가게/세션에서 사용할 수 있는 내 형식이 안전한 세션 객체를 다음과 같다:

string s = MySession.Current.MyString;
s = "new value";
MySession.Current.MyString = s;

이 솔루션은 결과는 여러 가지 이점:

  • 나는 형식이 안전 세션(더 이상 유형-캐스트)
  • 나는 문서 모든 세션을 기반으로 데이터(주석으로 대중의 속성에 인스턴스에 연결해야 합)
  • 을 때에 새로운 요소를 추가하면 세션이 없을 검색 솔루션을 확인하는 경우에는 동일한 세션 키를 이미 사용되는 다른 곳이다.

업데이트: 여기에 VB 버전(자동으로 변환됩 C#버전)입니다.죄송하지만 모르겠 VB 고지 않았다,그래서 작성하는 방법을 알고 있는 속성에 VB:

Public Class MySession
    ' Private constructor (use MySession.Current to access the current instance).
    Private Sub New()
    End Sub

    ' Gets the current session.
    Public Shared ReadOnly Property Current() As MySession
        Get
            Dim session As MySession = TryCast(HttpContext.Current.Session("__MySession__"), MySession)
            If session = Nothing Then
                session = New MySession()
                HttpContext.Current.Session("__MySession__") = session
            End If
            Return session
        End Get
    End Property

    ' My session data goes here:
    Public MyString As String
    Public MyFlag As Boolean
    Public MyNumber As Integer
End Class

다른 팁

해당 값이 관련된 경우에만. 그렇지 않으면 평범한 오래된 상수를 사용하십시오.

어떨까요 :-

public static class  SessionVar
{
  public static readonly string myVar1 = "myVar1";
  public static readonly string myVar2 = "myVar2";
  public static readonly string myVar3 = "myVar3";
  public static readonly string myVar4 = "myVar4";
}

이것은 당신이 사용할 수 있습니다 :-

session(SessionVar.myVar1) = something;

이와 같은 클래스를 사용하여 입력 된 세션/캐시 래퍼를 만듭니다. get/set에 추가 코드를 추가해야 할 수도 있지만이를 남겨 두겠습니다.

internal class SessionHelper
{
    private const string  myVar1Key = "myvar1";

    public static int MyVar1
    {
        get
        {
            return (int)System.Web.HttpContext.Current.Session[myVar1Key];
        }
        set
        {
            System.Web.HttpContext.Current.Session[myVar1Key] = value;
        }
    }
}

C#에 대해 죄송합니다 ....

모든 문자열 키 참조를 제거하는 간단한 점을 위해서는 애플리케이션 범위에서 볼 수있는 글로벌 정적/공유 상수를 사용합니다.

그렇지 않으면 세션 변수에 대한 강력하게 입력 된 간단한 래퍼는 우수한 대안이며, 지능형 및 객체 브라우저 호환성을 얻는 것을 고려할 때 훨씬 더 친숙합니다.

내가 많은 가치를 가진 열거가되는 것을 볼 수있는 유일한 방법은 배열 또는 유사한 목록에 색인하는 데 사용되는 것입니다. 그러나 그때도 열거를 int에 던져야합니다.

따라서 모든 세션 변수 키로 애플리케이션 시작시로드 한 배열과 인덱스의 열거가있을 수 있습니다. 그러나 세션 객체가 httpsessionState에서 파생되면 ienumerable에서 파생되면 필요한 경우 세션 변수에 대해 Foreach 루프를 수행 할 수 있어야합니다.

나는이 질문이 얼마 전에 묻고 "답변"이 이미 선택되었다는 것을 알고 있습니다. 그러나 나는 방금 그것을 만났다. 마틴의 대답은 좋습니다. 그러나 앞으로이 문제를 우연히 발견하는 사람을 돕기 위해 세션을 다루는 매끄러운 방법을 원한다면이 읽기를 읽으십시오. 게시하다. 나는 당신이 더 쉬운 것을 찾을 것이라고 생각하지 않습니다.

나는 솔루션을 방지하는 특정의 단점을 다른 솔루션 게시 유지하여 구조물의 세션 변수를 그대로 유지됩니다.그것은 단순히 형식이 안전한 바로 가기를 얻고 세션을 설정 변수입니다.

그것은 C#지만,나는 게시된 어떤 자동 생성 VB.NET 니다.

최고의 솔루션을 보았(허용되는 대답을 하여 TheObjectGuy)필요로 하는 사용자 정의 클래스에 저장되는 세션 변수,그리고 다음을 뽑아에서 세션 속성에 액세스하는 무언가 다음과 같 MySessionClass.현재 있습니다.MyProperty.

이 문제는 현재 사용 중인 경우(또는 사용할 수 있는 미래에)뭔가 다른 것보다는 InProc 세션 상태 모드(참조하십시오 https://msdn.microsoft.com/en-us/library/ms178586%28v=vs.140%29.aspx다),전체 클래스를 직렬화를 통해 액세스하는 단일 제공합니다.

또한,당신은 잃는 것을 의미합페 및 ICollection 구현에 의해 제공되는 실제 세션이 필요하신 경우입니다.나의 솔루션,당신은 단순히 액세스는 실제 세션이 필요하신 경우에는 이 기능이 있습니다.

당신은 쉽게 사용할 수 있는 이러한 세션 변수 그리고 그들은 유형-안전합니다.그것은 함께 사용될 수 있 다음과 같은 문장 세션["MyProperty"],는 것이 허용의 변환을 위해 기존 프로젝트 중 하나를 참조한다.그래서:

int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;

가:

int myInt = SessionVars.MyInt; 
SessionVars.MyInt = 3;

여기에 실제의 클래스입니다.이 CallerMemberName 이 필요합니다.NET4.5 지만,경우에도 이전 버전을 사용하고 당신은 여전히 관리하여 명시적으로 전달하는 속성.또한,형식의 속성에 null 을 허용해야 합니다 그것을 행동이 정확히 동일한 기준으로 세션["MyProp"]통화 때문이 아닌 설정

public static class SessionVars
{
    private static T Get2<T>([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") 
    {
        if (HttpContext.Current.Session[propertyName] == null)
        {
            return default(T);
        }

        return (T)HttpContext.Current.Session[propertyName];
    }

    private static void Set2<T>(T value, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        HttpContext.Current.Session[propertyName] = value;
    }

    public static int MyInt { get { return Get2<int>(); } set { Set2<int>(value); } }
    public static bool MyBool { get { return Get2<bool>(); } set { Set2<bool>(value); } }
    public static string MyString { get { return Get2<string>(); } set { Set2<string>(value); } }
}

저는 심지어 코드 조각을 촉진하는 추가 이러한 속성:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>SessionVars Property</Title>
    <Author>kevinpo</Author>
    <Shortcut>sv</Shortcut>
    <Description>Adds a property for use in a SessionVars class</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>type</ID>
        <Default>int</Default>
      </Literal>
      <Literal>
        <ID>property</ID>
        <Default>PropertyName</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[public static $type$ $property$ { get { return Get2<$type$>(); } set { Set2<$type$>(value); } }]]>
    </Code>
  </Snippet>
</CodeSnippet>

나는 C#사람이다,그래서 이 VB.NET 은 자동으로 변환 http://converter.telerik.com/:

Public NotInheritable Class SessionVars
    Private Sub New()
    End Sub
    Private Shared Function Get2(Of T)(<System.Runtime.CompilerServices.CallerMemberName> Optional propertyName As String = "") As T
        If HttpContext.Current.Session(propertyName) Is Nothing Then
            Return Nothing
        End If
        Return DirectCast(HttpContext.Current.Session(propertyName), T)
    End Function

    Private Shared Sub Set2(Of T)(value As T, <System.Runtime.CompilerServices.CallerMemberName> Optional propertyName As String = "")
        HttpContext.Current.Session(propertyName) = value
    End Sub

    Public Shared Property MyInt() As Integer
        Get
            Return Get2(Of Integer)()
        End Get
        Set
            Set2(Of Integer)(value)
        End Set
    End Property
    Public Shared Property MyBool() As Boolean
        Get
            Return Get2(Of Boolean)()
        End Get
        Set
            Set2(Of Boolean)(value)
        End Set
    End Property
    Public Shared Property MyString() As String
        Get
            Return Get2(Of String)()
        End Get
        Set
            Set2(Of String)(value)
        End Set
    End Property
End Class

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top