HttpContext.Current在MVC4中创建函数异步时为null

VVR*_*493 2 asynchronous task-parallel-library asp.net-mvc-4

我目前正在研究VS2010-SP1中的MVC4.我在控制器类Asynchronous中创建了一个函数.作为其中的一部分,我创建了从AsyncController派生的控制器类,并添加了以下两个方法(请参阅下面的代码部分1和2).一个以Async结尾的方法(参见代码第1节)和另一个以Completed结尾的方法(参见代码第2节).问题出在模型类中我试图使用来自HttpContext的凭据访问我的web服务(参见下面的代码3).进行异步调用时,上下文为空.即,在新的线程中,httpcontext不可用.如何将上下文从主线程传递到创建的新线程.

代码第1节

public void SendPlotDataNewAsync(string fromDate, string toDate, string item)
{

         AsyncManager.OutstandingOperations.Increment();
                    var highChartModel = new HighChartViewModel();
                    Task.Factory.StartNew(() =>
                    {
                          AsyncManager.Parameters["dataPlot"] = 
highChartModel.GetGraphPlotPointsNew(fromDate, toDate, item);
                          AsyncManager.OutstandingOperations.Decrement();
                      });

}
Run Code Online (Sandbox Code Playgroud)

第2节

 public JsonResult SendPlotDataNewCompleted(Dictionary<string, List<ChartData>> 
 dataPlot)
 {
      return Json(new { Data = dataPlot });
 }
Run Code Online (Sandbox Code Playgroud)

第3节

public List<MeterReportData> GetMeterDataPointReading(MeterReadingRequestDto 
meterPlotData)
{

            var client = WcfClient.OpenWebServiceConnection<ReportReadingClient,   
IReportReading>(null, (string)HttpContext.Current.Session["WebserviceCredentials"] ?? 
string.Empty);

                try
                {
                    return 
ReadReportMapper.MeterReportReadMap(client.GetMeterDataPointReading(meterPlotData));
                }
                catch (Exception ex)
                {
                    Log.Error("MetaData Exception:{0},{1},{2},{3}", 
ex.GetType().ToString(), ex.Message, (ex.InnerException != null) ? 
ex.InnerException.Message : String.Empty, " ");
                    throw;
                }
                finally
                {
                    WcfClient.CloseWebServiceConnection<ReportReadingClient, 
IReportReading> (client);
                }

                }
Run Code Online (Sandbox Code Playgroud)

nos*_*tio 5

HttpContext.Currentnull因为您的任务是在没有AspNetSynchronizationContext同步上下文的池线程上执行的.

用途TaskScheduler.FromCurrentSynchronizationContext():

Task.Factory.StartNew(() =>
    {
        AsyncManager.Parameters["dataPlot"] =
            highChartModel.GetGraphPlotPointsNew(fromDate, toDate, item);
        AsyncManager.OutstandingOperations.Decrement();
    },
    CancellationToken.None,
    TaskCreationOptions.None, 
    TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)