WCF和ASP.NET - Server.Execute抛出对象引用未设置为对象的实例

时间:2010-03-29 18:38:30

标签: asp.net wcf

我有一个调用WCF服务的ASP.NET页面。此WCF服务使用BackgroundWorker在我的服务器上异步创建ASP.NET页面。奇怪的是,当我执行

WCF服务

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void PostRequest(string comments)
{
   // Do stuff


   // If everything went o.k. asynchronously render a page on the server. I do not want to
   // block the caller while this is occurring. 
   BackgroundWorker myWorker = new BackgroundWorker();
   myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork);
   myWorker.RunWorkerAsync(HttpContext.Current);
}

private void myWorker_DoWork(object sender, DoWorkEventArgs e)
{
  // Set the current context so we can render the page via Server.Execute
  HttpContext context = (HttpContext)(e.Argument);
  HttpContext.Current = context;

  // Retrieve the url to the page
  string applicationPath = context.Request.ApplicationPath;
  string sourceUrl = applicationPath + "/log.aspx";
  string targetDirectory = currentContext.Server.MapPath("/logs/");

  // Execute the other page and load its contents
  using (StringWriter stringWriter = new StringWriter())
  {
    // Write the contents out to the target url
    // NOTE: THIS IS WHERE MY ERROR OCCURS
    currentContext.Server.Execute(sourceUrl, stringWriter);

    // Prepare to write out the result of the log
    targetPath = targetDirectory + "/" + DateTime.Now.ToShortDateString() + ".aspx";
    using (StreamWriter streamWriter = new StreamWriter(targetPath, false))
    {
      // Write out the content to the file
      sb.Append(stringWriter.ToString());
      streamWriter.Write(sb.ToString());
    }
  }
}

奇怪的是,当执行currentContext.Server.Execute方法时,它会抛出“未设置为对象实例的对象引用”错误。这很奇怪的原因是因为我可以在监视窗口中查看currentContext属性。此外,Server不为null。因此,我不知道这个错误来自何处。

有人能指出我的原因可能是正确的方向吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

你正在使用HttpContext - 默认情况下通常可用于WCF(并且将是null) - 毕竟,WCF可以自我托管在IIS之外和ASP.NET管道。

如果您需要并想要使用HttpContext,您需要专门允许它并将其打开。在服务器的配置中,您需要:

<system.serviceModel>        
    <serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />    
</system.serviceModel>

并且您的服务类也应该用以下内容进行修饰:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class YourServiceImplementation : IYourService
......

结帐

广泛涵盖所有细节。