我需要幫助將以下 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
提交
取消