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

ASP.NET Core中文件上传至API时Image字段为null的问题排查

问题描述

选择文件后可在<img>元素中正常渲染该文件,但将其发送至API时,对象的其他字段均有值,仅Image字段为null。

相关代码

类定义

public class ImageDto2
{
    public IFormFile? Image { get; set; }
    public string Description { get; set; } = string.Empty;
    public string FileId { get; set; } = string.Empty;
    public string IncidentId { get; set; } = string.Empty;
}

WASM处理代码

protected async Task HandleValidSubmit()
{
    _validationMessage = string.Empty;
    var validationResult = await Validator!.ValidateAsync(_imageDto!);
    var user = await LocalStorageService!.GetItem<string>("access_token");

    if (validationResult.IsValid)
    {
        using (var content = new MultipartFormDataContent())
        {
            var fileContent = new StreamContent(_imageFile!.OpenReadStream());
            content.Add(fileContent, "Image");

            content.Add(new StringContent(_imageDto!.Description), "Description");
            content.Add(new StringContent(_imageDto!.IncidentId), "IncidentId");
            content.Add(new StringContent("0"), "FileId");

            HttpClient!.DefaultRequestHeaders.Clear();
            HttpClient!.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", user);
            HttpClient!.DefaultRequestHeaders.Accept.Clear();

            HttpClient!.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));
            var response= await HttpClient.PostAsync("/api/incidents/upload-image-web", content);

            if (response.IsSuccessStatusCode)
            {
                await Console.Out.WriteLineAsync("success");
            } else
            {
                await Console.Out.WriteLineAsync("failed");
            }
        }
    }
    else 
        _validationMessage = validationResult.Errors?.FirstOrDefault()!.ToString();
}

API接口代码

[HttpPost("upload-image-web")]
public async Task<ActionResult> UploadImage([FromForm] ImageDto2 imageDto)
{
    // ...
}
解决方案

问题出在两个关键细节:

  1. 文件表单数据缺少文件名和媒体类型:ASP.NET Core在绑定IFormFile时,需要表单项包含文件名信息,否则无法将流识别为文件对象。
  2. 错误设置Accept请求头:Accept头用于指定客户端接受的响应格式,而非请求格式。MultipartFormDataContent会自动生成正确的Content-Type请求头,手动添加multipart/form-data到Accept完全多余,甚至可能干扰服务器解析。

修改后的WASM代码如下:

protected async Task HandleValidSubmit()
{
    _validationMessage = string.Empty;
    var validationResult = await Validator!.ValidateAsync(_imageDto!);
    var user = await LocalStorageService!.GetItem<string>("access_token");

    if (validationResult.IsValid)
    {
        using (var content = new MultipartFormDataContent())
        {
            var fileContent = new StreamContent(_imageFile!.OpenReadStream());
            // 为文件内容设置正确的媒体类型和文件名
            fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_imageFile.ContentType);
            content.Add(fileContent, "Image", _imageFile.Name);

            content.Add(new StringContent(_imageDto!.Description), "Description");
            content.Add(new StringContent(_imageDto!.IncidentId), "IncidentId");
            content.Add(new StringContent("0"), "FileId");

            HttpClient!.DefaultRequestHeaders.Clear();
            HttpClient!.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", user);
            HttpClient!.DefaultRequestHeaders.Accept.Clear();

            // 移除错误的Accept头设置,不需要指定接受multipart/form-data响应
            var response= await HttpClient.PostAsync("/api/incidents/upload-image-web", content);

            if (response.IsSuccessStatusCode)
            {
                await Console.Out.WriteLineAsync("success");
            } else
            {
                await Console.Out.WriteLineAsync("failed");
            }
        }
    }
    else 
        _validationMessage = validationResult.Errors?.FirstOrDefault()!.ToString();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:53:12