【问题标题】:ASP.NET Handler not working properlyASP.NET 处理程序无法正常工作
【发布时间】:2014-10-23 17:34:02
【问题描述】:

我在 C# 中创建了一个 Ashx 处理程序,它根据传递给我的 fileid 参数为我提供图像。我还编写了一个简单的工具提示预览脚本,但它不起作用。你可以看到图片正在加载,但是在加载之后,图片就消失了。

我怀疑问题出在 ASHX 处理程序中,因为如果我使用静态图像,它就可以正常工作。这是我的 ASHX 处理程序代码:

    public void ProcessRequest(HttpContext context)
    {
        string fileId = HttpUtility.UrlDecode(context.Request.QueryString["fileId"] ?? "") ?? "";
        string fullFileName = context.Server.MapPath("~/Uploads") + "\\" + fileId;

        using (FileStream s = File.Open(fullFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            context.Response.ContentType = HelperClasses.Utility.GetMimeTypeFromMagic(fullFileName);

            var buffer = new byte[s.Length];
            s.Read(buffer, 0, (int) s.Length);

            context.Response.BinaryWrite(buffer);
            context.Response.Write(buffer);

            s.Close();
        }
        context.Response.Flush();
        context.Response.Close();
    }

另外,我创建了a fiddle 来演示这个问题。

【问题讨论】:

  • 嘿,我认为这是 chrome 的问题,stackoverflow.com/questions/22219565/…
  • 你的处理程序很好;如果我将 URL 插入浏览器,我会得到图像。
  • GetMimeTypeFromMagic(顺便说一句,很棒的方法名称)返回正确的内容类型吗?
  • IE 中运行良好...
  • @JawwadAlam -- 这就是问题所在!现在效果很好!根据您的评论做出回答,我会接受。

标签: c# jquery asp.net ashx


【解决方案1】:

在您的代码中,行

context.Response.Close();

是问题所在。 close 方法会突然结束响应流,详见here 并查看此相关问题IIS & Chrome: failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING

context.Response.End();替换该行以正常结束响应。

【讨论】:

    【解决方案2】:

    您在响应结束时扔垃圾,特别是因为除了BinaryWrite 之外,您还调用了Response.Write。如果您查看处理程序的响应,则在末尾(字面意思):

    System.Byte[]

    显然这不是图片的一部分。此行应删除:

    context.Response.Write(buffer);
    

    我也会 avoid 做任何类似 Response.EndResponse.Close 的事情。让 ASP.NET 运行时来处理。

    更好的是,如果您使用的是 .NET Framework 4 或更早版本,您可以将整个事情简化为:

    s.CopyTo(context.Response.OutputStream);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 2016-05-06
      相关资源
      最近更新 更多