I have created one API in ASP.NET Core 3.1 project for file uploading. This api working fine when I called api from Postman or any other .NET Core project using HttpClient. But I am unable to call this api from Webform using WebClient.
[HttpPost("Upload")]
public IActionResult Upload([FromForm] IFormFile fileUpload)
{
ResponseViewModel responseModel = new ResponseViewModel();
try
{
if (fileUpload == null)
{
responseModel.Message = "Please select file.";
return BadRequest(responseModel);
}
//file upload to temp folder
string tempFilPathWithName = Path.GetTempFileName();
using (FileStream file = System.IO.File.OpenWrite(tempFilPathWithName))
{
fileUpload.CopyTo(file);
}
UploadFile uploadFile = new UploadFile()
{
FileName = fileUpload.FileName,
TempFilPathWithName = tempFilPathWithName
};
responseModel.Model = uploadFile;
responseModel.Message = "File successfully uploaded";
return Ok(responseModel);
}
catch (Exception ex)
{
responseModel.ExceptionMessage = ex.ToString();
responseModel.Message = "File upload failed.";
}
return BadRequest(responseModel);
}
public class ResponseViewModel
{
public object Model { get; set; }
public string ExceptionMessage { get; set; }
public string Message { get; set; }
}
After uploading file on server (where ASP.NET Core wep api project deploy) I will getting response like: uploaded file path and name.
It would be nicer if you could share your request code snippet in details but apart from this you could achieve the using HttpClient.
In addition to this, sending file request from ASP.NET webform project you would require MultipartFormDataContent so that you can implement your requirement accordingly.
Let's have a look on a quick demonstration how we can efficiently implement that in action:
File Upload From ASP.NET webform To Asp.net Core Web API:
Note: Important point to keep in find here, in StreamContent you should match request parameter as same as your controller parameter defination. In your scenario, your controller name is fileUpload; Thus, it should be matched exactly and last one is file name you want to pass which is mandatory and I kept that same but you can put anything. Otherwise, request would not reach to endpoint.
Response Model:
Output:
Last but not least, for API code snippet I have tested with your sample but I personally prefer following way and I like to keep my files under wwwroot.
API File Operation:
Note: If you would like to know more details on it you could check our official document here.