PNG文件Content-Type是Response.ContentType中的文本

时间:2012-05-16 16:02:18

标签: c# asp.net httpwebrequest httpresponse

我在模块中有以下代码,用于将Response的输入定向回浏览器。问题是我有一些来自第三方应用程序的PNG文件未正确呈现。还可以正确呈现其他PNG和JPG文件。问题文件的Content-Type将作为Text发送回来,导致它无法运行正确的输出类型代码。谁看过这个吗?关于如何解决这个问题的任何想法?

byte[] responsearr = ReadFully(response.GetResponseStream());
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
string responseStr = encoding.GetString(responsearr);

HttpContext.Current.Response.ContentType = response.ContentType;

if (response.ContentType.Contains("image") || response.ContentType.Contains("document"))
{
    if (response.ContentType.Contains("image"))
        Debug.WriteLine(encoding.GetString(responsearr));
    HttpContext.Current.Response.OutputStream.Write(responsearr, 0, responsearr.Length);
}
else
{
    HttpContext.Current.Response.Write(responseStr);
}

HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();

在我可以向Apache管理员验证MIME类型分配之前,我已将代码更新为以下内容。

void RouteRequest(ProxyMappingElement mapping)
{
    //does a whole bunch of stuff between here and there .... 

    // Important problem piece

    byte[] responsearr = ReadFully(response.GetResponseStream());
    System.Text.Encoding encoding = System.Text.Encoding.UTF8;
    string responseStr = encoding.GetString(responsearr);
    HttpContext.Current.Response.ContentType = GetContentType(response);

    if (HttpContext.Current.Response.ContentType.Contains("image") ||       HttpContext.Current.Response.ContentType.Contains("document"))
    {
        HttpContext.Current.Response.OutputStream.Write(responsearr, 0, responsearr.Length);
    }
    else
    {
        HttpContext.Current.Response.Write(responseStr);
    }

    HttpContext.Current.Response.Flush();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

private string GetContentType(HttpWebResponse response)
{
    return HttpContext.Current.Request.Url.ToString().Substring(
        HttpContext.Current.Request.Url.ToString().Length - 3, 3).ToLower().Equals("png")
               ? (HttpContext.Current.Response.ContentType = "image/png")
               : (HttpContext.Current.Response.ContentType = response.ContentType);
}

0 个答案:

没有答案