使用RestSharp上传文件返回状态码:422。

huangapple go评论75阅读模式
英文:

Uploading a file with RestSharp returns status-code: 422

问题

当我尝试使用RestSharp上传文件到API时,我得到以下响应:

'Error calling UploadFile: {"message":"The given data was invalid.","errors":{"file":["The file field is required."]}}'

当我使用他们的平台上传文件到API时,一切都按预期运行。请求如下:

curl -X POST "https://{URL}/v1/customer/files/ef02f89c-accf-4ca5-a05a-456cf65242d3" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "file=@dancing-penguins.gif;type=image/gif"

响应如下:

Code 200

Response body
Download
{
  "id": "ef02f89c-accf-4ca5-a05a-456cf65242d3",
  "fileName": "dancing-penguins.gif"
}

我的上传文件的代码如下:

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;

    var fileParams = new Dictionary<string, FileParameter> { ["file"] = FileParameter.Create(file.FileName, fileData, file.FileName, MapContentTypeFromExtension(file.FileName)) };
    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);

    foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);

    request.RequestFormat = DataFormat.Json;
    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;
}

希望这些信息对你有所帮助。

英文:

When I try to upload a file to an API with the help of RestSharp, I get the response:

&#39;Error calling UploadFile: {&quot;message&quot;:&quot;The given data was invalid.&quot;,&quot;errors&quot;:{&quot;file&quot;:[&quot;The file field is required.&quot;]}}&#39;

When I upload the file to the API using their plattform everything works as expected.
Request:

curl -X POST &quot;https://{URL}/v1/customer/files/ef02f89c-accf-4ca5-a05a-456cf65242d3&quot; -H &quot;accept: application/json&quot; -H &quot;Content-Type: multipart/form-data&quot; -F &quot;file=@dancing-penguins.gif;type=image/gif&quot;

Response:

Code 200
	
Response body
Download
{
  &quot;id&quot;: &quot;ef02f89c-accf-4ca5-a05a-456cf65242d3&quot;,
  &quot;fileName&quot;: &quot;dancing-penguins.gif&quot;
}

My code to upload the file:

        private ApiResponse&lt;File&gt; UploadFileWithHttpInfo(File file, byte[] fileData)
		{
			var pathParams = new Dictionary&lt;string, string&gt;() { [&quot;id&quot;] = Configuration.ApiClient.ParameterToString(file.Id) };
			var headerParams = new Dictionary&lt;string, string&gt;(Configuration.DefaultHeader);

			string httpHeaderAccept = &quot;application/json&quot;;
			if (httpHeaderAccept != null)
				headerParams.Add(&quot;Accept&quot;, httpHeaderAccept);

			if (!string.IsNullOrEmpty(Configuration.AuthString))
				headerParams[&quot;Authorization&quot;] = Configuration.AuthString;

			var fileParams = new Dictionary&lt;string, FileParameter&gt; { [&quot;file&quot;] = FileParameter.Create(file.FileName, fileData, file.FileName, MapContentTypeFromExtension(file.FileName)) };
			string path = &quot;/v1/customer/files/{id}&quot;;
			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);

			foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);

			// set user agent
			//RestClient.UserAgent = Configuration.UserAgent;
			request.RequestFormat = DataFormat.Json;
			InterceptRequest(request);
			var response = RestClient.Execute(request);
			InterceptResponse(request, response);

			Exception exception = ExceptionFactory(nameof(UploadFile), response);
			return exception == null ? new ApiResponse&lt;File&gt;(Configuration, response) : throw exception;
		}

Any help is appreciated.

答案1

得分: 0

我向RestSharp的AddFile方法传递了错误的参数。我传递的是文件名,而不是标签:“file”。

foreach (var param in fileParams) request.AddFile("file", param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
英文:

I passed the wrong argument to the RestSharps AddFile method. Instead of the tag: 'file', I passed the filename.

foreach (var param in fileParams) request.AddFile(&quot;file&quot;, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);

huangapple
  • 本文由 发表于 2023年2月6日 16:43:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定