programing tip

ASP.NET의 모든 클래스에서 세션 변수에 액세스하는 방법은 무엇입니까?

itbloger 2020. 6. 9. 08:18
반응형

ASP.NET의 모든 클래스에서 세션 변수에 액세스하는 방법은 무엇입니까?


내 응용 프로그램의 App_Code 폴더에 클래스 파일을 만들었습니다. 세션 변수가 있습니다

Session["loginId"]

내 수업 에서이 세션 변수에 액세스하고 싶지만 다음 줄을 쓸 때 오류가 발생합니다.

Session["loginId"]

누구나 ASP.NET 2.0 (C #)의 app_code 폴더에 생성 된 클래스 내의 세션 변수에 액세스하는 방법을 알려줄 수 있습니까?


(완전성을 위해 업데이트 됨) 다음을
사용하여 모든 페이지를 사용하거나 Session["loginId"]모든 클래스 (예 : 클래스 라이브러리 내부)를 사용하여 제어하거나 세션 변수에 액세스 할 수 있습니다.System.Web.HttpContext.Current.Session["loginId"].

그러나 원래 답변을 읽으십시오 ...


항상 ASP.NET 세션 주위에 래퍼 클래스를 사용하여 세션 변수에 대한 액세스를 단순화합니다.

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

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

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

이 클래스는 ASP.NET 세션에 하나의 인스턴스를 저장하고 다음과 같이 모든 클래스에서 형식 안전 방식으로 세션 속성에 액세스 할 수 있도록합니다.

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

이 방법에는 몇 가지 장점이 있습니다.

  • 그것은 많은 유형 캐스팅에서 당신을 구해줍니다.
  • 애플리케이션 전체에서 하드 코딩 된 세션 키를 사용할 필요가 없습니다 (예 : Session [ "loginId"]
  • MySession의 특성에 대한 XML 문서 주석을 추가하여 세션 항목을 문서화 할 수 있습니다.
  • 세션 변수를 기본값으로 초기화 할 수 있습니다 (예 : null이 아닌지 확인).

스레드 HttpContext를 통해 세션에 액세스하십시오.

HttpContext.Current.Session["loginId"]

The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.


The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:

The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.

MSDN explains how this is possible:

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext.

However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.


I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA


This should be more efficient both for the application and also for the developer.

Add the following class to your web project:

/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
{
protected internal static void Save<T>(string sessionName, T value)
{
    HttpContext.Current.Session[sessionName] = value;
}

protected internal static T Get<T>(string sessionName)
{
    return (T)HttpContext.Current.Session[sessionName];
}

public static int? WhatEverSessionVariableYouWantToHold
{
    get
    {
        return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
    }
    set
    {
        Save(nameof(WhatEverSessionVariableYouWantToHold), value);
    }
}

}

Here is the implementation:

SessionCentralized.WhatEverSessionVariableYouWantToHold = id;

In asp.net core this works differerently:

public class SomeOtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void TestSet()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public void TestGet()
    {
        var message = _session.GetString("Test");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

참고URL : https://stackoverflow.com/questions/621549/how-to-access-session-variables-from-any-class-in-asp-net

반응형