I have a created a server code which accepts file through post command.
Server side code:
app.MapPost("/upload2", async (IFormFile file) =>
{
List<string> validextensions = new List<string>() { ".xlsx" };
string extension = Path.GetExtension(file.FileName);
if (!validextensions.Contains(extension))
{
return $"Extention is not valid({string.Join(",", validextensions)})";
}
string filename = "File1" + extension;
string path = @"D:/";
using FileStream stream = new FileStream(Path.Combine(path, filename), FileMode.Create);
file.CopyToAsync(stream);
return filename;
});
I believe this code is ok because it works fine in postman. However, I failed sending file through C#!
Client code:
public async Task SendExcelFileToServer(string filepath, string filename, string InnerAddress)
{
try
{
// Create an instance of HttpClient
using (var httpClient = new HttpClient())
{
// Set the request URI
string requestUri = ServerAddressTextBox.Text.Trim() + InnerAddress;
// Create multipart form data content
using (var form = new MultipartFormDataContent())
{
string antiforgeryToken, cookie;
(antiforgeryToken, cookie) = await GetAntiforgeryToken();
// Add file part
using (var fileContent = new ByteArrayContent(File.ReadAllBytes(filepath)))
{
//form.Headers.ContentType = MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//form.Add(fileContent, "file", filename);
// This Is obligatory inn .net8! :)
// Add the RequestVerificationToken header
form.Headers.Add("RequestVerificationToken", "CfDJ8IobTqaCf0xCi3hgie2deVpx3DCZeGmVD28L6YAsM51Szh1AF0afHexqh7O768rwdYqOqLx8ph3yM86l7bg_phwtnHFspWVdFBtKScLlooFE_10wA6HidiiMZT6TbqZsR5Q1l6C7qJ9Zcuj_1bhxt10");
// Add the cookie header
form.Headers.Add("Cookie", ".AspNetCore.Antiforgery.p8-WnM9DThg=CfDJ8IobTqaCf0xCi3hgie2deVrgEG5nQyY-SHCgXvPCDh8LFzaqG7fOX41qgeGCXUcjPKgAPvPRqEUgYhzhHLTfcnClNq5rmQIZ-CkycC_V0vzBYhSgXdCVnL_9_ftvHXhYl7S3RR575hPwsAUvKg9D8kQ");
//form.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
//httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
//httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
//httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
// Send post request
HttpResponseMessage response = await httpClient.PostAsync(requestUri, form);
// Check response
response.EnsureSuccessStatusCode();
}
}
}
}
catch
{
MessageBox.Show("Try sending data again and check your connection!");
}
}
I added
RequestVerificationToken to my postman post command manually. Also, I added it to my post command in C#.
As you can see based on my comments in client code, I have tried so many options. But, they all failed.