使用RestSharp上传文件返回422状态码,提示file字段缺失求助
问题分析与解决
问题诊断
你遇到的file字段必填错误,核心原因是RestSharp构造的请求和curl的有效请求存在两个关键差异:
- 错误设置请求格式:代码中
request.RequestFormat = DataFormat.Json;会强制RestSharp按JSON格式处理请求,干扰multipart/form-data类型的表单构造,导致API无法识别文件字段。 - 表单字段名不匹配:调用
AddFile时使用了文件名作为表单字段名,而API期望的字段名是file(对应curl中的-F "file=@...")。
修复方案
1. 移除JSON请求格式设置
删除这行代码:
request.RequestFormat = DataFormat.Json;
multipart/form-data类型的文件上传不需要指定JSON格式,这行代码会添加不必要的请求头并破坏表单结构。
2. 修正AddFile的表单字段名
将原来的AddFile调用:
foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
修改为:
foreach (var param in fileParams) request.AddFile(param.Key, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
这里param.Key对应你fileParams字典中的键"file",和curl请求中的字段名完全匹配,确保API能正确识别文件参数。
简化写法(可选)
因为你已经有文件的字节数组fileData,可以直接使用AddFileBytes简化代码,替代循环处理fileParams:
request.AddFileBytes("file", fileData, file.FileName, MapContentTypeFromExtension(file.FileName));
修复后的完整代码片段
private ApiResponse<File> UploadFileWithHttpInfo(File file, byte[] fileData) { var pathParams = new Dictionary<string, string>() { ["id"] = Configuration.ApiClient.ParameterToString(file.Id) }; var headerParams = new Dictionary<string, string>(Configuration.DefaultHeader); string httpHeaderAccept = "application/json"; if (httpHeaderAccept != null) headerParams.Add("Accept", httpHeaderAccept); if (!string.IsNullOrEmpty(Configuration.AuthString)) headerParams["Authorization"] = Configuration.AuthString; string path = "/v1/customer/files/{id}"; Method method = Method.POST; var request = new RestRequest(path, method); foreach (var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); foreach (var param in headerParams) request.AddHeader(param.Key, param.Value); // 直接添加文件字节数组,指定正确的表单字段名"file" request.AddFileBytes("file", fileData, file.FileName, MapContentTypeFromExtension(file.FileName)); // set user agent //RestClient.UserAgent = Configuration.UserAgent; InterceptRequest(request); var response = RestClient.Execute(request); InterceptResponse(request, response); Exception exception = ExceptionFactory(nameof(UploadFile), response); return exception == null ? new ApiResponse<File>(Configuration, response) : throw exception; }
验证逻辑
修复后,RestSharp会构造和curl完全一致的multipart/form-data请求:
- 表单字段名为
file - 请求头自动设置为
multipart/form-data(无需手动添加) - 文件数据正确附加到请求中
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

