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

如何修改.NET接口代码,从数据库返回含图片、id、价格、名称的指定行数据

代码修改方案

你需要先调整SQL查询逻辑读取额外字段,再根据你的业务场景选择合适的返回格式,以下是具体修改方案:

核心修改点

  • 修改SQL查询语句,增加需要返回的id、price、name字段
  • 替换原来的ExecuteScalar方法,改用MySqlDataReader读取多个字段的值
  • 调整返回值结构,同时返回结构化字段和图片内容

方案1:Base64封装JSON返回(实现最简单)

这种方案把图片转成Base64字符串,和其他字段一起封装为JSON对象返回,前端可以直接解码Base64显示图片,适合图片体积不大的场景。
首先新增DTO类封装返回数据:

public class CourseInfoWithImage
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public string Name { get; set; }
    public string ImageBase64 { get; set; }
}

修改后的接口代码:

[HttpGet("{id}")]
public IActionResult RetrieveFile(int id)
{
    int courseId = 0;
    decimal price = 0;
    string courseName = string.Empty;
    string pathImage = string.Empty;

    // 调整SQL查询字段
    string query = @"select id, price, name, image from mydb.courses where id=@id";
    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");

    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myCommand.Parameters.AddWithValue("@id", id);
            // 改用DataReader读取多字段
            using (MySqlDataReader reader = myCommand.ExecuteReader())
            {
                if (reader.Read())
                {
                    courseId = reader.GetInt32("id");
                    // 这里的类型要和你数据库price字段的实际类型匹配
                    price = reader.GetDecimal("price");
                    courseName = reader.GetString("name");
                    pathImage = reader.GetString("image");
                }
                else
                {
                    return NotFound("未查询到对应课程数据");
                }
            }
            mycon.Close();
        }
    }

    // 读取图片转Base64
    byte[] imageBytes = System.IO.File.ReadAllBytes(pathImage);
    string imageBase64 = Convert.ToBase64String(imageBytes);

    // 封装返回对象
    var result = new CourseInfoWithImage
    {
        Id = courseId,
        Price = price,
        Name = courseName,
        ImageBase64 = imageBase64
    };

    return Ok(result);
}

方案2:Multipart多部分返回(适合大体积图片)

如果图片体积较大,转Base64会额外增加30%左右的传输体积,此时可以返回multipart/form-data格式,同时返回结构化数据和二进制图片流:

[HttpGet("{id}")]
public IActionResult RetrieveFile(int id)
{
    int courseId = 0;
    decimal price = 0;
    string courseName = string.Empty;
    string pathImage = string.Empty;

    string query = @"select id, price, name, image from mydb.courses where id=@id";
    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");

    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myCommand.Parameters.AddWithValue("@id", id);
            using (MySqlDataReader reader = myCommand.ExecuteReader())
            {
                if (reader.Read())
                {
                    courseId = reader.GetInt32("id");
                    price = reader.GetDecimal("price");
                    courseName = reader.GetString("name");
                    pathImage = reader.GetString("image");
                }
                else
                {
                    return NotFound("未查询到对应课程数据");
                }
            }
            mycon.Close();
        }
    }

    var multipartContent = new MultipartFormDataContent();
    // 添加结构化字段
    multipartContent.Add(new StringContent(courseId.ToString()), "Id");
    multipartContent.Add(new StringContent(price.ToString()), "Price");
    multipartContent.Add(new StringContent(courseName), "Name");
    // 添加二进制图片流
    var fs = new FileStream(pathImage, FileMode.Open);
    multipartContent.Add(new StreamContent(fs), "Image", Path.GetFileName(pathImage));

    return new OkObjectResult(multipartContent)
    {
        StatusCode = StatusCodes.Status200OK
    };
}

注意事项

  • 如果数据库中price字段不是decimal类型,需要修改对应代码里的类型和读取方法,比如是int就用GetInt32("price")
  • 如果图片格式不固定为jpeg,可以把图片的ContentType也存在数据库中,查询出来后在返回时动态指定
  • 建议对读取的pathImage做路径合法性校验,限制在允许的存储目录范围内,避免路径遍历漏洞

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:48:02