[英]C# multipart form data httpclient upload csv service
I have a windows service that is uploading a multipart data form in C#.我有一个 windows 服务正在上传 C# 中的多部分数据表单。 It is uploading a csv with authentication variables in the form: a key, a context, and a uuid.它正在上传带有身份验证变量的 csv,格式为:密钥、上下文和 uuid。 The variables are set in a custom Token class.这些变量在自定义令牌 class 中设置。 Each time I try to upload, I get a 403 error.每次我尝试上传时,都会收到 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);
}
}
}
}
I am trying to upload to an Amazon S3 Bucket, and the bucket is handled through a third party.我正在尝试上传到 Amazon S3 存储桶,该存储桶是通过第三方处理的。 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.但是,当我在http://www.webhook.com中尝试此操作时,它成功上传并显示输入的表单值。
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.这个 multipartformdata & httpclient 对我来说是新的,所以我不知道我错过了什么,如果有的话。
Original code: https://dotnetcodr.com/2013/01/10/how-to-post-a-multipart-http-message-to-a-web-service-in-c-and-handle-it-with-java/原代码: 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 Errors: https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-forbidden-error/ AWS S3 错误: https://aws.amazon.com/premiumsupport/knowledge-center/s3-403-forbidden-error/
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.在我的开发过程中,我确实创建了自己的 S3 存储桶,并添加了 NuGet AWS S3 class,它能够成功上传文件。 Now that I am uploading to a 3rd party bucket, I keep getting a 403 error.现在我正在上传到第 3 方存储桶,我不断收到 403 错误。 Thanks!谢谢!
I went the route of using Postman to create my request, then got the generated code for C# with the RestSharp NuGet Package.我使用 Postman 来创建我的请求,然后使用 RestSharp NuGet Z2092Z5027DBBBBDC86 获取 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);
}
}
Highly recommend going that route for multipart form-data.强烈建议采用多部分表单数据的路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.