1

いくつかのクラスで、静的な「Current」プロパティを実装して、HttpContext.Current プロパティのように動作させようとしました。コンテキストまたはリクエスト ヘッダーのみに依存するものは、通常どおり動作します。ただし、現在の Session オブジェクトに依存するものは失敗します。これらの場合、Session オブジェクトは 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() メソッドからセッションを取得することはできません。

何かご意見は?

ありがとう!

4

4 に答える 4

1

非常に簡単な答え: Session が初期化される前に、どこか (まだわからない) が EducationalUnit.Current にヒットしています。セッションの null をテストする条件を追加し、黙って何もしないと、エラーはなくなり、すべてが機能しました。

そして、何かに影響を与えないように見えるので、おそらく EducationalUnit.Current にヒットする必要はありません...

フィードバックをお寄せいただきありがとうございます!

補遺: この問題は、EducationalUnit.Current が Page プロパティから間接的にヒットされたときに発生していました。

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()
于 2012-05-30T00:26:44.780 に答える
0

問題は、HttpContext.Currentは静的プロパティですが、返されるオブジェクトのプロパティは静的プロパティではないということです。を実行しようとするprivate static HttpSessionState Session { get { return HttpContext.Current.Session; } }と、値は最初の参照に入力され、その後は更新されません。そのため、HttpContext.Current.Sessionが保持する最初の値を取得します。nullを保持しました。これは参照がないため、取得するオブジェクトへの参照がなく、そのプロパティへの呼び出しは常にnullを返します。私が本当に言えるのは、そうしないことだけです。

さらに、チェーンのどこでクラスが呼び出されるかによっては、有用な値にアクセスできない場合があります。多くの場合、静的クラスでは、メソッドにHttpContextを引数として使用させる方が簡単です。

わかりました...Sessionが実際にどのように機能するかを見てみましょう。カバーの下で、これは次のとおりです。

    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; 
        } 
    }  

チェーンのどこでも静的ではないことに注意してください。Webアプリケーションは特定のライフサイクルに従います。ライフサイクルのどこにいるかによっては、セッションが常に存在するとは限りません。...(時間切れです。続行します。)

于 2012-05-29T22:08:07.173 に答える
0

これは、尋ねられた質問とは無関係のものかもしれませんが、誰かを助けるかもしれません.

私は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"];

        }
    }
于 2016-12-22T09:10:21.483 に答える
0

試すHttpContext.Current.Session

于 2012-05-29T21:57:03.180 に答える