C# HttpPost Authentication Error Resolution

I try to send files to the server using C# httpPost, but authentication failure continues to occur
However, transmission that is implemented simply with Python is being transmitted, but username and password are entered through copy and paste and declared in the variable, so there is no mistake, but an authentication error occurs

I checked the result of encoding with other people, but I think it’s the same, but C# is failing to authenticate and only python is successful

How do I fix it to make C# also successful in authentication?

I thought I would just need to create a code to send files with the C# code and add a header for authentication, but it doesn’t work

C# code

try
{

username = 'aaaaa'
password = 'aa0000'
  using (var httpClient = new HttpClient())
  {
    string authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

    // 이미지 파일의 모든 바이트를 읽음
    byte[] imageData = File.ReadAllBytes(_sImagePath);
    var vImageContent = new ByteArrayContent(imageData);

    string sFileExtension = Path.GetExtension(_sImagePath).ToLower();
    string sMimeType;

    switch (sFileExtension)
    {
      case ".jpg":
      case ".jpeg":
        sMimeType = "image/jpeg";
        break;
      case ".png":
        sMimeType = "image/png";
        break;
      case ".bmp":
        sMimeType = "image/bmp";
        break;
      case ".gif":
        sMimeType = "image/gif";
        break;
      default:
        sMimeType = "application/octet-stream";
        break;
    }

    vImageContent.Headers.ContentType = new MediaTypeHeaderValue(sMimeType);
    using (var form = new MultipartFormDataContent())
    {

      form.Add(vImageContent, "file", Path.GetFileName(_sImagePath));

      HttpResponseMessage response = await httpClient.PostAsync(_sServerUrl, form);

      if (!response.IsSuccessStatusCode)
      {
        string responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"이미지 업로드 실패: {response.StatusCode}");
        Console.WriteLine($"응답 내용: {responseContent}");

        Console.WriteLine("요청 헤더:");
        foreach (var header in httpClient.DefaultRequestHeaders)
        {
          Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}");
        }

        Console.WriteLine("요청 내용:");
        foreach (var content in form)
        {
          Console.WriteLine(content.Headers);
        }
      }
      return response.IsSuccessStatusCode;
    }
  }
}
catch (Exception ex)
{
  // 예외 처리
  System.Windows.MessageBox.Show($"Failed to upload image: {ex.Message}");
  return false;
}

python code

import requests
from requests.auth import HTTPBasicAuth

cdnServerUrl = 'http://111.111.111.111:8000/TEST'
targetFile = r'C:TestTEST_I_240718_140919.jpeg'
username = 'aaaaa'
password = 'aa0000'

with open(targetFile, 'rb') as img_file:
    files = {'file': img_file}
    response = requests.post(cdnServerUrl, files=files, auth=HTTPBasicAuth(username, password))

if response.status_code == 200:
    print('이미지 업로드 성공')
else:
    print('이미지 업로드 실패:', response.status_code)
    print('응답 내용:', response.text)

print(response.request.headers)

                client.DefaultRequestHeaders.UserAgent.ParseAdd("python-requests/2.32.3");
                client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate");
                client.DefaultRequestHeaders.Accept.ParseAdd("*/*");
                client.DefaultRequestHeaders.Connection.ParseAdd("keep-alive");
                client.DefaultRequestHeaders.Add("Cookie", "HFS_SID_=0.926163150230423");

In order to copy the python request information as it is, I added the following, and when encoding, I made the string differently, and I tried ASCII, not UTF8
But they all have authentication errors

It seems that you have the whole info of headers, so you can try to clear DefaultRequestHeaders before adding info into it.

client.DefaultRequestHeaders.Accept.Clear();

or

client.DefaultRequestHeaders.Clear();

Besides, the server returns what http result code?

New contributor

WangDaChui is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật