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

Unity对接ASP.Net WebApi上传CSV数据失败,请求技术帮助

问题分析与解决方案

核心问题原因

Unity端请求的Content-Type与WebAPI接口的接收方式不匹配,导致服务器无法正确解析请求体:

  • 字符串上传时错误设置Content-Type: text/json,但实际传递的是纯文本而非JSON格式字符串;
  • CSV上传时使用multipart/form-data格式,但WebAPI接口用[FromBody] string接收,无法解析表单数据;
  • WebAPI的[FromBody] string默认要求请求体是带双引号包裹的JSON格式字符串,而非普通纯文本。

修复方案:纯文本上传(适配现有接口逻辑)

1. Unity端代码修正

将请求的Content-Type改为text/plain,直接传递CSV文本内容:

// 上传CSV文本内容
private IEnumerator UploadCsvTextCoroutine(string csvContent)
{
    byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(csvContent);
    using (UnityWebRequest www = new UnityWebRequest(serverUrl + "/read-employee-csv", "POST"))
    {
        www.uploadHandler = new UploadHandlerRaw(textBytes);
        www.downloadHandler = new DownloadHandlerBuffer();
        // 关键:设置正确的Content-Type为纯文本
        www.SetRequestHeader("Content-Type", "text/plain");

        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("上传成功!服务器响应:" + www.downloadHandler.text);
        }
        else
        {
            Debug.LogError("上传失败:" + www.error);
        }
    }
}

// 从本地文件读取CSV后上传
private IEnumerator UploadCsvFileAsTextCoroutine(string filePath)
{
    string csvContent = File.ReadAllText(filePath, Encoding.UTF8);
    yield return UploadCsvTextCoroutine(csvContent);
}

2. WebAPI端代码修正

添加text/plain格式的输入支持,让接口能正确接收纯文本请求体:

// 在Program.cs(.NET 6+)中配置输入格式化器
builder.Services.AddControllers(options =>
{
    options.InputFormatters.Insert(0, new TextPlainInputFormatter());
});

// 自定义纯文本输入格式化器类
public class TextPlainInputFormatter : TextInputFormatter
{
    public TextPlainInputFormatter()
    {
        SupportedMediaTypes.Add("text/plain");
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        using var reader = new StreamReader(context.HttpContext.Request.Body, encoding);
        string content = await reader.ReadToEndAsync();
        return await InputFormatterResult.SuccessAsync(content);
    }
}

// 修改Controller接口
[HttpPost("read-employee-csv")]
public IActionResult GetEmployeeCSV([FromBody] string csvContent)
{
    if (string.IsNullOrEmpty(csvContent))
    {
        return BadRequest("未接收到CSV内容");
    }

    using var stream = new MemoryStream(Encoding.UTF8.GetBytes(csvContent));
    var employees = _csvService.ReadCSV<Coordinate>(stream);
    return Ok(employees);
}

替代方案:直接上传文件流(更适合CSV文件场景)

如果需要上传完整的CSV文件,推荐用表单上传方式,WebAPI用IFormFile接收:

1. Unity端文件上传代码

private IEnumerator UploadCsvFileCoroutine(string filePath)
{
    var formData = new WWWForm();
    // 参数名"file"需与WebAPI接口参数名一致
    formData.AddBinaryData("file", File.ReadAllBytes(filePath), Path.GetFileName(filePath), "text/csv");

    using (UnityWebRequest www = UnityWebRequest.Post(serverUrl + "/upload-csv-file", formData))
    {
        yield return www.SendWebRequest();

        if (www.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("文件上传成功!服务器响应:" + www.downloadHandler.text);
        }
        else
        {
            Debug.LogError("文件上传失败:" + www.error);
        }
    }
}

2. WebAPI接口代码

[HttpPost("upload-csv-file")]
public IActionResult UploadCsvFile(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return BadRequest("请选择要上传的CSV文件");
    }

    using var stream = file.OpenReadStream();
    var employees = _csvService.ReadCSV<Coordinate>(stream);
    return Ok(employees);
}

调试建议

  • 在Unity中用抓包工具(如Charles)查看实际发送的请求头和请求体,确认格式是否符合预期;
  • 在WebAPI中添加日志,打印请求的Content-Type和请求体内容,排查解析问题;
  • 用Swagger测试接口时,选择对应的Content-Type(text/plain或multipart/form-data)并填入正确的测试数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:53:10