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?
WangDaChui is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.