0

私は mvc プロジェクトを作成しており、Unity でテストしています。

コンテキストからデータを取得および設定するセッション サービスを作成しました (以下を参照)。

public class SessionService : ISessionService
{

    private IConfiguration _Configuration;
    private ILog _Log;
    private HttpContext _Context;

    private T GetSession<T>(string key)
    {
        return (T)HttpContext.Current.Session[key];
    }

    private void SetSession(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public SessionService(HttpContext context, IConfiguration configuration, ILog log)
    {
        _Configuration = configuration;
        _Log = log;
        _Context = context;

    }

    public SessionModel SessionModel
    {
        get
        {
            if (GetSession<SessionModel>("SESSION_SESSIONMODEL") == null)
            {
                SetSession("SESSION_SESSIONMODEL", new SessionModel());
            }
            return GetSession<SessionModel>("SESSION_SESSIONMODEL");
        }
        set { SetSession("SESSION_SESSIONMODEL", value); }
    }

}

私のテストでは、(以下のように)セッションをモックして送信しています

_TestSessionService = new SessionService(HttpContext.Current, Configuration, _TestLog);

var httpRequest = new HttpRequest("", "", "");
var httpResponce = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer =
            new HttpSessionStateContainer("id",
                                           new SessionStateItemCollection(),
                                           new HttpStaticObjectsCollection(),
                                           10,
                                           true,
                                           HttpCookieMode.AutoDetect,
                                           SessionStateMode.InProc,
                                           false);
httpContext.Items["AspSession"] =
            typeof(HttpSessionState)
            .GetConstructor(
                                BindingFlags.NonPublic | BindingFlags.Instance,
                                null,
                                CallingConventions.Standard,
                                new[] { typeof(HttpSessionStateContainer) },
                                null)
            .Invoke(new object[] { sessionContainer });
HttpContext.Current = httpContext;

これはすべてテストでは正常に機能しますが、Web アプリを実行すると、httcontect を介して sessionservice クラスに送信されないため、unity が失敗します。

テストやアプリの使用のために mvc 内でセッションを処理する最善の方法を示す完全な例を提供してください。

4

0 に答える 0