Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to call .net core web API having two paramter one is IFormFile and another is simple string. But not able to call from console application in C#
Below is API code
 [HttpPost]
        [RequestSizeLimit(200 * 1024 * 1024)]
        [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
     public string Upload
(IFormFile file, [FromForm]string ClientName)
        {
            string fileName = file.FileName;
            fileName = "E:\\2021\\" + fileName;
            using (FileStream fs = System.IO.File.Create(fileName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            return "";
        }




What will be the best approach to call above web api method in C# console application.

What I have tried:

My Client application console is as follow which code is generated from Postman but not able to integrate in application with actual value where file is store in physical location.

var client = new RestClient("https://localhost:44363/api/HostToHost/Upload");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "94b86506-cfb0-476e-aaa4-a10b083e32ad");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"F:\\Vishal\\tt12.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"ClientName\"\r\n\r\ntest\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Posted
Updated 1-Aug-21 23:00pm

1 solution

You're sending the local path of the file, rather than the content of the file. That won't work - the server has no access to your local disk.

Rather than using AddParameter and manually encoding the request body, use AddFile to add the file:
C#
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "94b86506-cfb0-476e-aaa4-a10b083e32ad");
request.AddHeader("cache-control", "no-cache");
request.AddFile("file", System.IO.File.ReadAllBytes(@"F:\Vishal\tt12.txt"), "tt12.txt");
request.AddParameter("ClientName", "test");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900