You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET调用WebService后报错:无法将System.String转换为System.Byte[]

报错根因

报错根因为WebService XML序列化机制导致的类型不匹配:

  • 未接入WebService时,直接从数据库读取poster字段,ADO.NET会将二进制格式的图片数据映射为System.Byte[]类型,强转逻辑可正常运行
  • 接入WebService后,数据通过XML格式传输,字节数组会被自动序列化为Base64编码的字符串,通过XmlNodeReader将数据加载到DataSet时,poster字段的类型已经变为System.String,此时再执行(byte[])dr["poster"]强转就会抛出对应报错
修复方案

直接修改OnRowDataBound方法里的图片地址生成逻辑,兼容两种数据类型即可:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dr = (DataRowView)e.Row.DataItem;
        string base64Poster;
        // 兼容直连数据库返回字节数组、WebService返回Base64字符串两种场景
        if (dr["poster"] is byte[] posterBytes)
        {
            base64Poster = Convert.ToBase64String(posterBytes);
        }
        else
        {
            base64Poster = dr["poster"]?.ToString() ?? string.Empty;
        }
        string imageUrl = "data:image/jpg;base64," + base64Poster;                          
        (e.Row.FindControl("Image1") as Image).ImageUrl = imageUrl;
    }
}

修改后无需调整其他逻辑,直接运行即可正常加载图片。

内容的提问来源于stack exchange,提问作者user16515314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 08:30:05