从静态方法访问HttpContext.Session

时间:2018-10-30 07:07:28

标签: asp.net-core asp.net-core-2.1

从放置在单独任务中的静态方法访问HttpContext.Session时出现以下错误:

  

尚未为此应用程序或请求配置会话。

我使用this article来实现对控制器外部HttpContext的访问

从控制器中,我调用了用于检索图像数据的静态方法:

public static void CreateDummyGallery(Gallery gallery)
{
    Logger.LogDebug(LogModule.Dummy, $"Starting gallery creation.");
    Task.Factory.StartNew(() =>
    {
        try
        {
            List<DummyPicture> pictures;
            using (var context = new MyzeumContext())
            {
                int top = 10;
                pictures = context.DummyPictures.FromSql($"SELECT * FROM dummypictures ORDER BY RAND() LIMIT {top}").ToList();
            }
            Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
            Parallel.ForEach(pictures, picture => {
                using (WebClient client = new WebClient())
                {
                 }
             });
            Logger.LogDebug(LogModule.Dummy, $"Done retrieving images.");
        }
        catch(Exception e)
        {
            Logger.LogError(LogModule.Server, e.Message, e);
        }
    });
}

在Logger.LogDebug()中出现问题,因为这是我访问HttpContext的地方:

public void LogDebug(LogModule module, string message, Exception stackTrace = null)
{
    Log record = new Log();
    record.Module = module;
    record.ThreadId = Environment.CurrentManagedThreadId;
    record.SessionId = HttpContextHelper.Current?.Session?.Id;
    record.Message = message;
    record.Logged = DateTime.UtcNow;
    if(stackTrace != null)
    {
        record.Message += $" :{stackTrace.StackTrace}";
    }
    queue.Enqueue(record);
}

99%的问题发生在任务内部的第一次呼叫中:

Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
但是,在应用程序启动后,整个任务块就可以正常工作,并且不会引发任何异常。按照以下要求开始问题。

0 个答案:

没有答案
相关问题