2012-05-29 2 views
1

저는 몇 개의 클래스에 대해 HttpContext.Current 속성처럼 동작하도록 정적 "현재"속성을 구현하려고했습니다. 컨텍스트에만 의존하거나 요청 헤더는 정상적으로 작동합니다. 그러나 현재 Session 개체에 종속 된 개체는 실패합니다. 이러한 경우, 세션 개체가 null로 나타납니다.NET - 정적 메서드에서 세션 개체가 null입니다.

// THIS WORKS 
private static HttpContext Context { get { return HttpContext.Current; } } 

// THIS APPEARS TO YIELD NULL 
private static HttpSessionState Session { get { return HttpContext.Current.Session; } } 

public static EducationalUnit Current 
{ 
    get 
    { 
     if (Context.Items["EducationalUnit.Current"] == null) 
     { 
      SetCurrent(); 
     } 
     return (EducationalUnit)Context.Items["EducationalUnit.Current"]; 
    } 

    set 
    { 
     Context.Items["EducationalUnit.Current"] = value; 
    } 
} // Current 


// I've tried a few things here, to scope out the status of the Session: 
private static void SetCurrent() 
{ 
    // shows "null" 
    throw new Exception(Session); 

    // shows "null" 
    throw new Exception(Session.SessionID); 

    // also shows "null" 
    throw new Exception(HttpContext.Current.Session); 

    // shows "Object reference not set to an instance of an object." 
    throw new Exception(HttpContext.Current.Session.SessionID); 

    // this, however, properly echos my cookie keys! 
    JavaScriptSerializer js = new JavaScriptSerializer(); 
    throw new Exception(js.Serialize(Context.Request.Cookies.Keys.ToString())); 

} // SetCurrent() 

내가, 내 인생의에서 setCurrent() 메소드에서 세션의 보류를 얻을 수 없습니다.

의견이 있으십니까?

감사합니다.

답변

1

아주 간단한 대답 : 어딘가에 무엇이 있는지 확실하지 않습니다. 아직) 세션이 초기화되기 전에 EducationalUnit.Current를 치고있다. 조건을 추가하여 세션을 null로 테스트하고 아무것도하지 않으면 오류가 사라지고 모든 것이 작동합니다.

그리고 ... 그것은 어떤 영향을 미칠 것 같지 않기 때문에 아마, 일 필요는 없다 피드백에 대한

감사를 EducationalUnit.Current을 때리고 무엇이든!

칙 :

public partial class client_configuration : System.Web.UI.Page 
{ 
    // 
    // The problem occurs here: 
    // 

    private Client c = Client.Current; 

    // 
    // Client objects refer to EducationalUnit.Current, which attempts 
    // to use the Session, which doesn't exist at Page instantiation time. 
    // 
    // (The assignment can safely be moved to the Page_Load event.) 
    // 


    protected void Page_Load(object sender, EventArgs e) 
    { 
     // etc. 
    } 
} 

을 그리고 여기에 최종 (작업) EducationalUnit 코드입니다 :

private static HttpContext Context { get { return HttpContext.Current; } } 
private static HttpSessionState Session { get { return HttpContext.Current.Session; } } 


public static EducationalUnit Current 
{ 
    get 
    { 
     if (Context.Items["EducationalUnit.Current"] == null) 
     { 
      SetCurrent(); 
     } 
     return (EducationalUnit)Context.Items["EducationalUnit.Current"]; 
    } 

    set 
    { 
     Context.Items["EducationalUnit.Current"] = value; 
    } 
} // Current 


private static void SetCurrent() 
{ 
    if (Session == null) 
    { 
     throw new Exception("Session is not initialized!"); 
    } 
    else 
    { 
     try 
     { 
      Guid EUID = new Guid(Session["classroomID"].ToString()); 
      Current = new EducationalUnit(); 
      Current.GetDetails(EUID); 
     } 
     catch 
     { 
      Current = new EducationalUnit(); 
     } 
    } 
} // SetCurrent() 
+0

이 코드를 실제 코드로 업데이트 할 수 있습니다. 내일 내가 다시 사무실에있을 때. 아마 당신이 기대하는 것 일 겁니다. 하지만, 어쨌든 모든 사람들이 예상대로 작동하는지 확인하기 위해 게시 할 것입니다. 사실, 우주에 질서가 있습니다 ... – svidgen

0

HttpContext.Current.Session

+0

로하고 문제가 해결되지 않을 경우, 그것을 시도하는 방법 –

+0

에 매개 변수로 세션 상태 (또는 당신이 그것을 필요)를 전달합니다. SetCurrent 메서드에서 _throw 새 Exception ... _ 행을 각각 시도했습니다. 처음 세 개는 모두 null을 반환합니다. – svidgen

+0

가능하다면 쉽게 접근 할 수있는 {ClassName} .Current 객체를 제공하는 목적을 무효로하고 있습니다. – svidgen

0

귀하의 문제가 HttpContext.Current 정적 속성입니다 반면, 개체의 속성이 반환되지 않습니다 있다는 점이다보십시오. private static HttpSessionState Session { get { return HttpContext.Current.Session; } }을 시도하면 값이 첫 번째 참조에 채워지고 그 이후에는 업데이트되지 않습니다. 이 때문에 HttpContext.Current.Session이 보유한 첫 번째 값을 얻습니다. 그것은 참조가 없으므로 null을 가졌으므로 get에 대한 참조가 없으며 해당 속성에 대한 호출은 항상 null을 반환합니다. 내가 너에게 정말로 말할 수있는 것은 그렇게하지 않는 것 뿐이다.

또한 체인이 호출되는 위치에 따라 유용한 값에 액세스하지 못할 수도 있습니다. 종종 정적 클래스를 사용하면 메서드가 HttpContext를 인수로 사용하는 것이 더 안전합니다.

좋아요 ... 이제 당신이해야하는 것은 이것이다 내부적으로, 세션이 실제로 어떻게 작동하는지 살펴 보자 : 그것은 어디서나 체인의 정적없는

SessionStateModule _sessionStateModule; // if non-null, it means we have a delayed session state item 

    public HttpSessionState Session { 
     get { 
      if (_sessionStateModule != null) { 
       lock (this) { 
        if (_sessionStateModule != null) { 
         // If it's not null, it means we have a delayed session state item 
         _sessionStateModule.InitStateStoreItem(true); 
         _sessionStateModule = null; 
        } 
       } 
      } 

      return (HttpSessionState)Items[SessionStateUtility.SESSION_KEY]; 
     } 
    } 

    public IDictionary Items { 
     get { 
      if (_items == null) 
       _items = new Hashtable(); 

      return _items; 
     } 
    } 

하는 것으로. 웹 응용 프로그램은 특정 수명주기를 따르고 있으며 수명주기에 따라 세션이 항상 존재하는 것은 아닙니다 .... (시간 초과 됨, 계속 진행)

+0

나는 잘 모르겠다. 그러면 HttpContext.Current에서 Request 및 Response 객체에 액세스 할 수있는 이유는 무엇입니까? – svidgen

+0

HttpContext.Current는 이미 존재하는 개체에 대한 정적 참조이기 때문입니다. 개체가 업데이트되면 참조를 통해 개체에 대한 액세스가 여전히 유지되므로 해당 참조를 통해 업데이트 된 참조/값을 제공하여 속성에 정상적으로 액세스 할 수 있습니다. – JamieSee

+0

나는 그것이 기존의 객체에 대한 정적 레퍼런스 (게터)를 이해하고있다. Session 속성이 존재하지 않는 이유는 설명하지 않습니다. 기본 객체에 대한 업데이트로 인해 참조가 중단되는 이유는 설명하지 않습니다. 나는 다른 사람들에게 이것이 어째서는 안되는지 확신 할 수 없다면 혼란 스럽습니다. http://stackoverflow.com/questions/1913821/is-there-a-way- 세션에서 개체를 정적 컨텍스트에서 가져 오기 http://stackoverflow.com/questions/2804256/is-it-safe-to-access-asp-net-session-variables-through -static-properties-of-a-st – svidgen

0

것은이있을 수 있습니다 EducationalUnit.Current이 페이지 속성에서 간접적으로 명중 할 때 문제가 발생했다 그 질문과 무관 한 것이지만 누군가를 도울 수 있습니다.

나는 Generic Handler (.ashx)을 가지고 있는데, 정적 인 메소드 인 객체 데이터 소스를 가지고있는 일부 사용자 컨트롤의 결과를 보냈습니다. 이러한 정적 메서드는 세션 개체를 활용했습니다. 통하다. HttpContext.Current.Session.

그러나 Session 개체는 null입니다.

세션 개체에 액세스하려면 일반 처리기를 사용할 때 처리기 클래스에 마커 인터페이스 IReadOnlySessionState을 구현해야한다는 것을 발견했습니다.

public class AjaxHandler : IHttpHandler, IReadOnlySessionState 
     { 
     public void ProcessRequest(HttpContext context) 
      { 
      /* now both context.Session as well as 
    HttpContext.Current.Session will give you session values. 
    */ 
      string str = AjaxHelpers.CustomerInfo(); 

      } 

     } 

public static class AjaxHelpers 
    { 
     public static string CustomerInfo() 
     { 
      //simplified for brevity. 
return HttpContext.Current.Session["test"]; 

     } 
    } 
관련 문제