猿问

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

我需要帮助将以下 Python 代码转换为 c# .net。此代码将文本文件发布/上传到网络服务器。Python 脚本已经过测试并且可以正常工作。我已经尝试了一些使用 HTTPClient 和 WebRequest 的解决方案,但没有成功。任何指导将不胜感激。


# request a session

client = requests.session()


# Establish the URL

newurl = 'https://localhost/filedist/upload/'

source_file = 'data/test.txt'


headers = {'Authorization': 'Token MYTOKEN'}


# Populate the values with our environment and target path

values = 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 + "\""

            };



米琪卡哇伊
浏览 383回答 1
1回答

开心每一天1111

我不是 100% 对此,但我认为您不能以这种方式设置授权标头。尝试使用客户端授权标头类型。client.DefaultRequestHeaders.Authorization&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;AuthenticationHeaderValue("Token",&nbsp;"MYTOKEN");
随时随地看视频慕课网APP

相关分类

Python
我要回答