c# - 通用处理程序不返回值

标签 c# asp.net generic-handler

处理程序未返回图像。如果我删除条件语句,处理程序将返回图像。这是我的代码

public void ProcessRequest(HttpContext context)
    {
        string sid = "JUN15MBACHN001";
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        connection.Open();
        SqlCommand command = new SqlCommand("select suppassportphoto from studdetails where sregno=" + sid, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        Byte[] br = (Byte[])dr[0];
        if (br.Length > 1)
        {
            context.Response.BinaryWrite((Byte[])dr[0]);
        }          
        else
        {
            string path = context.Server.MapPath("~/image/emptymalepic.jpg");
            byte[] byteArray = File.ReadAllBytes(path);
            context.Response.BinaryWrite(byteArray);
        }
        connection.Close();
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

我不知道我哪里错了?任何帮助将不胜感激。

最佳答案

首先,我建议以不同的方式进行转换,因为您的代码可能会导致无效转换异常:

Byte[] br = dr[0] as Byte[];

然后检查是否为空

if (br != null && br.Length > 1)

然后写入文件:

context.Response.ContentType = "image/jpeg"; // or whatever type you're using
context.Response.BinaryWrite(br);

并替换

context.Response.End();

HttpContext.Current.ApplicationInstance.CompleteRequest();

因为我注意到有些浏览器不喜欢 Response.End()

希望这是有用的。祝你好运!

关于c# - 通用处理程序不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369826/

相关文章:

c# - 分配字节数组对性能至关重要吗?

c# - 从文本文件中读取固定宽度的记录

c# - Asp.Net Core 2.x HttpContext.Current 不可用

c# - 当 form[].element 被禁用时,Form.Key 消失

c# - 插入后不会立即更改 Blazor 文本

javascript - 如何合成和压缩 Javascripts (.net ajax) 以获得最佳性能

c# - 如何将此 SQL 查询转换为 LINQ (OVER (PARTITION BY Date))

c# - 如何在另一个应用程序中使用一个应用程序中使用的 Elasticsearch 索引

jquery - 在 ASP.NET 中使用通用处理程序对 jQuery AJAX 调用进行故障排除

c# - 与通用处理程序交互