亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 代碼到 c# .net 用于 HTTP Post 到 API

Python 代碼到 c# .net 用于 HTTP Post 到 API

米琪卡哇伊 2021-08-07 17:13:22
我需要幫助將以下 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");


查看完整回答
反對 回復 2021-08-07
  • 1 回答
  • 0 關注
  • 436 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號