2010-04-13 60 views
2

我已经为js文件实现了一个HttpHandler。这个HttpHandler的工作是本地化js文件的内容。所以处理程序会选择js文件的内容,对它们进行本地化并写入响应对象。 但问题是处理程序导致“远程主机关闭连接”时,它用于长文件。 以下是我认为错误是由以下行HttpHandler导致“远程主机关闭了连接”错误

context.Response.ContentType = "application/javascript"; 
context.Response.Output.Write(convertedFile); 
context.Response.Flush(); 

错误就这样产生 远程主机关闭了连接造成的HttpHandler的

using System; 
    using System.Collections.Generic; 
    using System.Globalization; 
    using System.IO; 
    using System.Reflection; 
    using System.Text.RegularExpressions; 
    using System.Threading; 
    using System.Web; 
    using System.Web.SessionState; 
    using System.Xml.Linq; 

    namespace ProjectLocalization 
    { 
     /// <summary> 
     /// HTTP Handler to handle .js file localized resources by replacing Resources tag 
     /// </summary> 
     public class JSFileResourceHandler : IHttpHandler, IRequiresSessionState 

     { 
     // Regex pattern to extract the resource place holders. 
     private const string RESOURCEPATTERN = @"<\x25{1}\x24{1}\s*Resources\s*:\s*(?<declaration>\w+\s*,\s*\w+)\s*%>"; 

     //Regex pattern to extract resource location settings. 
     private const string SETTINGSPATTERN = @"<resourcesettings>(?>.|\n)+?resourceSettings>"; 

     //Caches the default culture set when the handler got instantiated. 
     private CultureInfo defaultCulture; 

     public delegate CultureInfo OnApplyCulture(); 
     public static event OnApplyCulture ApplyCulture; 

     // Initializes a new instance of the class.   
     public JSFileResourceHandler() 
     { 
      defaultCulture = Thread.CurrentThread.CurrentCulture; 
     } 




     // Gets a value indicating whether another request can use 
     // the True if the instance is reusable; otherwise, false. 
     public bool IsReusable 
     { 
      get { return true; } 
     } 

     // Enables processing of HTTP Web requests by a custom HttpHandler 
     // that implements the interface. 
     // HttpContext: its object that provides references to the intrinsic server objects (for example, Request, 
     // Response, Session, and Server) used to service HTTP requests. 
     public void ProcessRequest(HttpContext context) 
     { 
      context.Response.Buffer = false; 

      // Retrieve culture information from session 
      if (ApplyCulture != null) 
      { 
       //Call ApplyCulture(delegate), is ApplyCutlture Return NULL then default culture will be set. 
       CultureInfo culture = ApplyCulture() ?? defaultCulture; 
       if (culture != null) 
       { 
        // Set culture to current thread 
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture.Name); 
        Thread.CurrentThread.CurrentUICulture = culture; 
       } 
      } 
      string physicalFilePath = context.Request.PhysicalPath; 
      string fileContent = string.Empty; 
      string convertedFile = string.Empty; 

      // Determine whether file exists 
      if (File.Exists(physicalFilePath)) 
      { 
       // Read content from file 
       using (StreamReader streamReader = File.OpenText(physicalFilePath)) 
       { 
        fileContent = streamReader.ReadToEnd(); 
        if (!string.IsNullOrEmpty(fileContent)) 
        { 
         // Load resource location types 
         //Dictionary<string, System.Type> locationTypes = GetResourceLocationTypes(fileContent); 
         Boolean IsLocalized = IsLocalizationImplemented(fileContent); 
         // Find and replace resource place holders 
         convertedFile = IsLocalized ? ReplaceResourcePlaceholders(fileContent) : fileContent;//, locationTypes); 
        } 
       } 
      } 
      context.Response.ContentType = "application/javascript"; 
      context.Response.Output.Write(convertedFile); 
      context.Response.Flush(); 
     } 


     private static bool IsLocalizationImplemented(string strFileContent) 
     { 
      try 
      { 
       bool IsLocalize = false; 
       Match settingsMatch = Regex.Match(strFileContent, SETTINGSPATTERN, RegexOptions.IgnoreCase); 
       while (settingsMatch.Success) 
       { 
        string Value = settingsMatch.Groups[0].Value.Replace("///", String.Empty).Replace("//", String.Empty); 
        XElement Settings = XElement.Parse(Value); 

        //Load Value that it is localized or not. 
        if (Settings.Element("Resource").Attribute("IsLocalize") != null) 
        { 
         String strIsLocalized = Settings.Element("Resource").Attribute("IsLocalize").Value; 
         settingsMatch = settingsMatch.NextMatch(); 
         if (strIsLocalized.ToUpper() == @"TRUE") IsLocalize = true; 
        } 
       } 
       return IsLocalize; 
      } 
      catch 
      { 
       return false; 
      } 
     } 


     //Replaces the resource placeholders.   
     //fileContent:Content of the file 
     //return:File content with localized strings 
     private static string ReplaceResourcePlaceholders(string fileContent) 
     { 
      string outputString = fileContent; 
      Match resourceMatch = Regex.Match(fileContent, RESOURCEPATTERN); 

      while (resourceMatch.Success) 
      { 
       // Determine whether a valid match was found 
       if (resourceMatch.Groups["declaration"] != null) 
       { 
        // Extract resource arguments -> always two 
        // arguments expected: 1. resource location name, 2. resource name 
        string[] arguments = 
         resourceMatch.Groups["declaration"].Value.Split(','); 

        if (arguments.Length < 2) 
        { 
         throw new ArgumentException("Resource declaration"); 
        } 

        string resourceLocationName = arguments[0].Trim(); 
        string resourceName = arguments[1].Trim(); 

        // Load resource string 
        string localizedValue = ""; 
        try 
        { 
         localizedValue = Convert.ToString(HttpContext.GetGlobalResourceObject(resourceLocationName, resourceName)); 
         localizedValue = localizedValue.Replace("\\'", "~"); 
         localizedValue = localizedValue.Replace("'", "~"); 
         localizedValue = localizedValue.Replace("~", "\\'"); 
        } 
        catch 
        { 
         localizedValue = "ERROR WHILE LOCALIZATION!!!"; 
        } 
        // Replace place holder 
        outputString = outputString.Replace(resourceMatch.Groups[0].Value, localizedValue); 
       } 

       // Find next regex match 
       resourceMatch = resourceMatch.NextMatch(); 
      } 



return outputString; 
     } 
    } 
} 

的代码。错误代码是0x80072746。

在System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(字节[]状态,字节[]报头,的Int32 keepConnected,的Int32 totalBodySize,的Int32 numBodyFragments,IntPtr的[] bodyFragments,的Int32 [] bodyFragmentLengths,的Int32 doneWithSession,的Int32 finalStatus,布尔&异步)在System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(布尔isFinal)在System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(布尔finalFlush)在System.Web.HttpResponse.Flush(布尔finalFlush)在System.Web.HttpResponse .Flush()System.Web.HttpWriter.Write(String s)在System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()在System.Web上的ProjectLocalization.JSFileResourceHandler.ProcessRequest(HttpContext上下文) .HttpApplication.ExecuteStep(IExecutionStep步骤,布尔型& completedSynchronously)

任何人都可以提出一个解决方案.....

回答

0

你尝试过摆脱调用的冲洗()?这是我看来唯一可疑的部分。

相关问题