C#多部分表单数据httpclient上传CSV服务 [英] C# multipart form data httpclient upload csv service
问题描述
我有一个Windows服务,该服务正在C#中上传多部分数据表单.它正在上载带有身份验证变量的csv,格式为:密钥,上下文和uuid.变量在自定义令牌类中设置.每次尝试上传时,都会出现403错误.
I have a windows service that is uploading a multipart data form in C#. It is uploading a csv with authentication variables in the form: a key, a context, and a uuid. The variables are set in a custom Token class. Each time I try to upload, I get a 403 error.
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 中尝试此操作时,它会成功上传并显示表单输入的值.
I am trying to upload to an Amazon S3 Bucket, and the bucket is handled through a third party. I have been told that my request is malformed; however, when I try this in http://www.webhook.com, it successfully uploads and shows the form values as entered.
我的代码中是否缺少某些内容?还是来自第三方的政策/许可问题?此多部分数据&httpclient对我来说是新手,所以我不会缺少我想要的东西.
Is there something that I am missing in my code? Or is it a policy/permission issue from the third party? This multipartformdata & httpclient is new to me, so I don't what I'm missing, if anything.
AWS S3错误: https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-forbidden-error/
AWS S3 Errors: https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-forbidden-error/
在开发过程中,我确实创建了自己的S3存储桶,并添加了NuGet AWS S3类,该类能够成功上传文件.现在,我正在上传到第3方存储分区,但我一直收到403错误.谢谢!
In my development process, I did create my own S3 bucket and I added the NuGet AWS S3 class, which was able to upload files successfully. Now that I am uploading to a 3rd party bucket, I keep getting a 403 error. Thanks!
推荐答案
我走了使用Postman创建请求的路线,然后使用RestSharp NuGet软件包获得了C#的生成代码.
I went the route of using Postman to create my request, then got the generated code for C# with the RestSharp NuGet Package.
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);
}
}
强烈建议您采用多份表格数据的方法.
Highly recommend going that route for multipart form-data.
这篇关于C#多部分表单数据httpclient上传CSV服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!