使用ASP.NET Core和C#向本地SQL Server上传图片报错求助
解决ASP.NET Core图片上传到SQL Server的问题
你遇到的两个问题根源:一是GET请求长度有限制,无法传输大体积的图片数据;二是客户端字节数组处理逻辑错误,且直接传递SQL语句存在严重安全风险。以下是针对性的解决方案:
1. 客户端代码修正
- 改用POST请求传输图片数据,规避GET的URI长度限制
- 正确读取图片的完整字节数组,避免数据截断或错误
- 不再传递SQL语句到服务端,仅发送图片数据
修正后的客户端代码:
OpenFileDialog opf = new OpenFileDialog(); if (opf.ShowDialog() != DialogResult.OK) return; // 增加文件选择判断 // 正确读取图片字节数据 byte[] imageData; using (var tmpStream = new MemoryStream()) { using (Image img = Image.FromFile(opf.FileName)) { img.Save(tmpStream, System.Drawing.Imaging.ImageFormat.Png); } imageData = tmpStream.ToArray(); // 直接获取完整的字节数组 } // 构造请求内容,以字节流形式传递 var content = new ByteArrayContent(imageData); content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); // 发送POST请求到服务端 HttpResponseMessage message = await Program.client.PostAsync("api/Image/UpdateLogo", content); message.EnsureSuccessStatusCode(); string response = await message.Content.ReadAsStringAsync();
2. 服务端代码修正(ASP.NET Core 标准写法)
- 使用ASP.NET Core Controller替代旧的
[WebMethod](ASMX技术已过时) - 服务端固定SQL语句,彻底杜绝SQL注入风险
- 直接接收请求体中的字节数据,存入SQL Server的二进制字段
修正后的服务端代码:
[ApiController] [Route("api/[controller]")] public class ImageController : ControllerBase { private readonly string _connString = "Data Source=(local);Initial Catalog=HA;Integrated Security=True"; [HttpPost("UpdateLogo")] public async Task<IActionResult> UpdateLogo() { string response; using (var connection = new SqlConnection(_connString)) { await connection.OpenAsync(); // 固定SQL语句,避免注入风险 string updateSql = "UPDATE CompSett SET Logo = @image"; using (var cmd = new SqlCommand(updateSql, connection)) { // 读取请求体中的图片字节数据 byte[] imageData = await Request.BodyReader.ReadToEndAsync().AsTask(); cmd.Parameters.Add(new SqlParameter("@image", SqlDbType.VarBinary) { Value = imageData }); int rowsAffected = await cmd.ExecuteNonQueryAsync(); response = rowsAffected > 0 ? "Record updated" : "Error"; } } return Ok(response); } }
关键注意事项
- 禁止传递SQL语句到服务端:直接传递
UpdateString会引发严重的SQL注入漏洞,攻击者可篡改、删除数据库数据 - GET与POST的选择:GET请求的URI长度受浏览器和服务器限制(通常仅几KB),图片Base64编码后体积会增大30%,完全不适合用GET传输
- 资源自动释放:使用
using语句自动释放Stream、SqlConnection、SqlCommand等资源,避免内存泄漏 - 数据库字段配置:确保SQL Server中
Logo字段的类型为varbinary(max),才能存储大体积的图片数据
内容的提问来源于stack exchange,提问作者user12235025
相关产品推荐
相关产品推荐

