我需要帮助将以下 Python 代码转换为 c# .net。此代码将文本文件发布/上传到网络服务器。Python 脚本已经过测试并且可以正常工作。我已经尝试了一些使用 HTTPClient 和 WebRequest 的解决方案,但没有成功。任何指导将不胜感激。# request a sessionclient = requests.session()# Establish the URLnewurl = 'https://localhost/filedist/upload/'source_file = 'data/test.txt'headers = {'Authorization': 'Token MYTOKEN'}# Populate the values with our environment and target pathvalues = dict(environment='dev', path='Business/Tools')files = dict(file=open(source_file, 'rb'))r = client.post(newurl, files=files, data=values, headers=headers)这是我的最新尝试,目前正在收到“禁止”错误。 public static async Task<string> UploadFile(string path, string fileName) { var client = new HttpClient(); string NewURL = "https://localhost/filedist/upload/"; string SourceFile = path; var content = new MultipartFormDataContent(); client.DefaultRequestHeaders.Add("Authorization", "Token MYTOKEN"); Stream fs = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None); content.Add(CreateFileContent(fs, fileName, "text/plain")); var parameters = new Dictionary<string, string> { { "environment", "dev" }, { "path", "Business/Tools" } }; content.Add(new FormUrlEncodedContent(parameters)); var response = await client.PostAsync(NewURL, content); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { string responseString = response.Content.ReadAsStringAsync().Result; return "true"; } else { return "false"; } } private static StreamContent CreateFileContent(Stream stream, string fileName, string contentType) { try { var fileContent = new StreamContent(stream); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "UploadedFile", FileName = "\"" + fileName + "\"" };
1 回答
开心每一天1111
TA贡献1836条经验 获得超13个赞
我不是 100% 对此,但我认为您不能以这种方式设置授权标头。尝试使用客户端授权标头类型。
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "MYTOKEN");
添加回答
举报
0/150
提交
取消