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

.NET Core中使用Refit上传图片返回400错误且数据为空

问题解决:Refit上传图片返回400 Bad Request且数据为空

问题分析

你的代码存在几个关键问题导致上传失败:

1. Service层方法名不匹配

Service层定义的方法是UpdaloadPhoto2,但Consume层调用的是productService.UploadPhoto,方法名拼写错误,会引发调用逻辑混乱。

2. StreamPart构造参数错误

StreamPart的第四个参数是表单字段名称,你传入的file.Name可能不符合API接收的字段要求,需要显式指定为"file",和Refit的[AliasAs("file")]、API端的[FromForm] IFormFile file保持一致。另外,流读取前未重置位置,可能导致数据读取不完整。

3. Consume层异步方法未使用await

Consume层调用异步方法时未加await,导致返回的是Task<bool>而非实际布尔值,判断逻辑完全失效。

修正后的代码

Refit接口(无需修改)

//Refit
[Multipart]
[Post("/api/products/{id}/uploadphoto")]
public Task<ApiResponse<bool>> UploadPhoto(int id, [AliasAs("file")] StreamPart streamPart);

Service层修正

//Service
public async Task<bool> UploadPhoto(int id, IFormFile file)
{
    using var stream = file.OpenReadStream();
    // 重置流位置到起始点,确保完整读取数据
    stream.Position = 0;
    // 显式指定表单字段名为"file",和API接收参数一致
    StreamPart streamPart = new StreamPart(stream, file.FileName, file.ContentType, "file");
    var res = await productClient.UploadPhoto(id, streamPart);
    if (res.IsSuccessStatusCode)
    {
        return true;
    }
    var content = res.Error.Content;
    AddErrors(content);
    return false;
}

Consume层修正

//Consume
[HttpPost("{id}/uploadphoto")]
public async Task<IActionResult> UploadPhoto(int id, [FromForm] IFormFile file)
{
    // 提前校验文件是否有效
    if (file == null || file.Length == 0)
    {
        return BadRequest("请选择要上传的图片");
    }
    
    var res = await productService.UploadPhoto(id, file);
    if (res) return Ok();
    return BadRequest(); 
}

额外检查项

  • 确认API端的/api/products/{id}/uploadphoto路由和参数接收逻辑完全匹配,确保没有路由前缀或参数名称不一致的问题。
  • 测试时可以抓包查看请求内容,确认multipart/form-data格式是否正确,文件数据是否已正常携带。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:36:24