C#多部分表单数据httpclient上传csv服务

C# multipart form data httpclient upload csv service

我有一项 windows 服务正在使用 C# 上传多部分数据表单。它正在上传一个 csv,其中包含以下形式的身份验证变量:密钥、上下文和 uuid。变量在自定义令牌 class 中设置。每次尝试上传时,我都会收到 403 错误。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UploadScheduler.Service
{
    class UploadHttp
    {
        // HttpClient is instantiated once per application
        static readonly HttpClient client = new HttpClient();
        //myUserKey and myUuid are redacted values
        public static string userKey = "myUserKey";
        public static string uuid = "myUuid";

        public static void UploadFile(FileInfo file, Token token, DateTime lwt, DateTime nwt)
        {
            FileInfo fi = new FileInfo(file.FullName);
            string fileName = fi.Name;
            byte[] fileContents = File.ReadAllBytes(fi.FullName);
            Uri webService = new Uri(token.Url);
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, webService);
            requestMessage.Headers.ExpectContinue = false;
            HttpWebRequest webRequest = WebRequest.CreateHttp(token.Url);
            webRequest.ServicePoint.Expect100Continue = false;
            MultipartFormDataContent multiPartContent = new MultipartFormDataContent();
            ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
            byteArrayContent.Headers.Add("Content-Type", "text/csv");
            multiPartContent.Add(byteArrayContent, "file", fileName);
            multiPartContent.Add(new StringContent(token.Key), "key");
            multiPartContent.Add(new StringContent(token.Context), "context");
            multiPartContent.Add(new StringContent(token.Uuid), "uuid");
            requestMessage.Content = multiPartContent;

            try
            {
                //Task<HttpResponseMessage> httpRequest = client.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
                Task<HttpResponseMessage> httpRequest = client.PostAsync(token.Url, multiPartContent, CancellationToken.None);
                HttpResponseMessage httpResponse = httpRequest.Result;
                HttpStatusCode statusCode = httpResponse.StatusCode;
                HttpContent responseContent = httpResponse.Content;

                if (responseContent != null)
                {
                    Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
                    String stringContents = stringContentsTask.Result;
                    Library.RecordUpload(file, lwt, nwt);
                }
            }
            catch (Exception ex)
            {
                Library.WriteLog("Upload Error: " + file.Name + " " + ex.Message);
                //Library.WriteLog(ex.StackTrace);
            }
        }
    }
}

我正在尝试上传到 Amazon S3 存储桶,而该存储桶是通过第三方处理的。我被告知我的请求格式不正确;但是,当我在 http://www.webhook.com 中尝试此操作时,它会成功上传并显示输入的表单值。

我的代码中是否遗漏了什么?还是来自第三方的 policy/permission 问题?这个 multipartformdata 和 httpclient 对我来说是新的,所以我不知道我缺少什么,如果有的话。

原代码:https://dotnetcodr.com/2013/01/10/how-to-post-a-multipart-http-message-to-a-web-service-in-c-and-handle-it-with-java/

AWS S3 错误:https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-forbidden-error/

在我的开发过程中,我确实创建了自己的 S3 存储桶并添加了 NuGet AWS S3 class,它能够成功上传文件。现在我正在上传到第 3 方存储桶,我不断收到 403 错误。谢谢!

我选择了使用 Postman 来创建我的请求,然后使用 RestSharp NuGet 包为 C# 生成了代码。

public static void UploadFile(FileInfo file, Token token, DateTime lwt, DateTime nwt)
        {
            string status = "";
            string reason = "";
            try
            {
                var client = new RestClient(token.Url);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddParameter("key", token.Key);
                request.AddParameter("uuid", token.Uuid);
                request.AddParameter("context", token.Context);
                request.AddFile("file", file.FullName);
                IRestResponse response = client.Execute(request);
                status = response.StatusCode.ToString();
                reason = response.ErrorMessage.ToString();
                Library.RecordUploadSuccess(file, lwt, nwt);
            }
            catch (Exception ex)
            {
                Library.RecordUploadError(file, status, reason);
                //Library.RecordUploadError(file, ex.Message, ex.StackTrace);
            }
        }

强烈建议为多部分表单数据采用这种方法。