C# Display.ashx不显示带有字符&;的图像名称;

C# Display.ashx不显示带有字符&;的图像名称;,c#,html,asp.net,webforms,C#,Html,Asp.net,Webforms,我遇到过这样的情况:Display.ashx成功显示来自Sql server的图像,其中只有字母(如咖啡或绿茶),但当图像名称保存为(咖啡和泡沫)时,它不会显示。请参阅下面的代码,我在Display类中的Img上放置了一个断点,当imagename为Coffee时,传递完整的字符串,但当imagename为Coffee&Froth时,它会剪切泡沫并只接受咖啡,这意味着它只接受字符前面的字符串-。请有人告诉我一个解决方法,这样它会接受整个字符串和字符。谢谢 public class Displa

我遇到过这样的情况:Display.ashx成功显示来自Sql server的图像,其中只有字母(如咖啡或绿茶),但当图像名称保存为(咖啡和泡沫)时,它不会显示。请参阅下面的代码,我在Display类中的Img上放置了一个断点,当imagename为Coffee时,传递完整的字符串,但当imagename为Coffee&Froth时,它会剪切泡沫并只接受咖啡,这意味着它只接受字符前面的字符串-。请有人告诉我一个解决方法,这样它会接受整个字符串和字符。谢谢

 public class Display : IHttpHandler
    {
        public Stream Displays(string Img)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString.ToString()))
            {
                string sql = string.Format("select top 1 img from Images where Name  = '{0}'", Img);

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Connection.Open();

                object imagevalue = cmd.ExecuteScalar();

                if (imagevalue != null && imagevalue != DBNull.Value)
                {
                    return new MemoryStream((byte[])imagevalue);
                }

                using (FileStream fs = File.OpenRead(HttpContext.Current.Server.MapPath(@"~/Content/noimage.png")))
                {
                    MemoryStream memStream = new MemoryStream();
                    memStream.SetLength(fs.Length);
                    fs.Read(memStream.GetBuffer(), 0, (int)fs.Length);
                    return memStream;
                }
            }
        }
    #endregion
这就是我所说的图像

 protected void Refresh_SelectedIndexChanged(object sender, EventArgs e)
        {
            // string id = CoffeeMenu.SelectedValue;
            Image1.ImageUrl = "~/Display.ashx?id=" + "Coffee & Froth";
            divSuccess.Visible = false;
          divError.Visible = false;
        }
HTML


对数据部分进行编码:

Image1.ImageUrl = "~/Display.ashx?id=" + Server.UrlEncode("Coffee & Froth");
您遇到的问题是&用于拆分url中的值,因此显示的额外参数如下所示:

?name=blah&resize=1920x1080&convert=png&rotate=90
因此,浏览器可能会将您的“咖啡和泡沫”请求为“咖啡+&+泡沫”,并且您的ashx会将其接收并解释为具有以下参数:

{
  "id": "Coffee ",
  " Froth": null
}

或者,从文件名中去掉任何不是数字或字母的内容;看起来这些东西存储在磁盘上时,您可以控制它们的命名,所以让生活变得简单


尝试
咖啡&;泡沫
咖啡%20%26%20泡沫

&
在HTML中用于表示
&

%20
对于
空格是十六进制的
%26
对于
&
是十六进制的。十六进制通常用于对URL中的特殊字符进行编码

完整ASCII表:

试试
“咖啡和泡沫”
。或者
“Coffee%20%26%20Froth”
也记录\打印sql以检查发送到数据库的内容谢谢@Mike67,将字符串替换为“Coffee%20%26%20Froth”效果很好。如果我可以问一个问题,具体是什么%20%26%20?
{
  "id": "Coffee ",
  " Froth": null
}