.net C# -使用HttpClient发送特定文件格式的API请求

ar7v8xwq  于 2023-03-31  发布在  .NET
关注(0)|答案(1)|浏览(135)

我需要将PNG图片发送到服务器(通过FormData),请求发送成功,但响应显示“错误的文件格式”(我没有权限访问服务器检查发生了什么)。
我目前使用的是.NET 6

private async Task RequestApiRegister(string bookingId, string name)
{
    using var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.TOKEN_REGISTER);

    try
    {
        string aliasId = bookingId + "__" + name;
        using FileStream fs = File.OpenRead(_filePath); // --> Absolute file path, ex: "E:\\Blabla\\IMG\\image_2023_03_24T19_54_30_9573981.png"

        var formData = new MultipartFormDataContent();
        formData.Add(new StringContent("secret"), "organization");
        formData.Add(new StringContent(aliasId), "aliasId");
        formData.Add(new StreamContent(fs), "images[]", Path.GetFileName(_filePath));

        string url = "https://some-endpoint.com/register";
        var response = await client.PostAsync(url, formData);
        //response.EnsureSuccessStatusCode();

        string sd = response.Content.ReadAsStringAsync().Result;
    } catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

我已经花了几个小时搜索,但还没有找到任何答案。这里是一些我已经尝试。

fkaflof6

fkaflof61#

经过几个小时的调试,我设法修复了这个问题。

pprivate async Task RequestApiRegister(string bookingId, string name)
{
    using var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.TOKEN_REGISTER);

    try
    {
        string aliasId = bookingId + "__" + name;
        
        var fileBytes = File.ReadAllBytes(_filePath);
        var fileContent = new ByteArrayContent(fileBytes);
        
        // This line below makes different!
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
        
        var formData = new MultipartFormDataContent
        {
            { new StringContent("internal-dev"), "organization" },
            { new StringContent(aliasId), "aliasId" },
            { fileContent, "images[]", Path.GetFileName(_filePath) }
        };

        string url = "https://some-endpoint.com/register";
        var response = await client.PostAsync(url, formData);
        //response.EnsureSuccessStatusCode();

        string sd = response.Content.ReadAsStringAsync().Result;
    } catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

相关问题