I need to post a file using WebRequest from an older .NET 3.5 app but the endpoint always got the file null
[HttpPost]
[Route("/api/app/savefile/")]
public async Task<IActionResult> Salavef(IFormFile file)
{
try
{
if (file == null || file.Length == 0)
return BadRequest('No file');
..............
C# NET3.5 code:
var uri = "https://localhost:44305/api/app/savefile";
var filePath = @"d:\data.dat";
var fileParameterName = Path.GetFileName(filePath);
var contentType = "text/plain; charset=utf-8";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string newLine = Environment.NewLine;
byte[] boundaryBytes = Encoding.ASCII.GetBytes(newLine + "--" + boundary + newLine);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}Content-Type: {3}{2}{2}";
string header = string.Format(headerTemplate, fileParameterName, filePath, newLine, contentType);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
requestStream.Write(headerBytes, 0, headerBytes.Length);
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4097];
Int32 bytesRead = fileStream.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
requestStream.Write(buffer, 0, bytesRead);
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
}
}
byte[] trailer = Encoding.ASCII.GetBytes(newLine + "--" + boundary + "--" + newLine);
requestStream.Write(trailer, 0, trailer.Length);
}
System.Net.WebResponse response = null;
try
{
response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
var responseText = responseReader.ReadToEnd();
}
}
}
catch (System.Net.WebException exception)
{
response = exception.Response;
if (response != null)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
}
response.Close();
}
}
finally
{
request = null;
}
got the code form Upload files with HTTPWebrequest (multipart/form-data)