Click here to Skip to main content
15,888,146 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i need to call an API in which one request parameter type is IFormFile and this api accept [FromForm] type request. i want to send my .CSV file in this parameter.

here is my code:-

string filepath = System.IO.Directory.GetCurrentDirectory() + "\\myFiles\\testfile.csv";
using (FileStream stream = System.IO.File.OpenRead(filepath))
{

    var myrequest = new Requestbody
    {
        data = new requestData()
        {
            ID = "",
            status = "",
            result = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
            {
                Headers = new HeaderDictionary(),
                ContentType = "application/csv"
            }
        }
    };

    string requestData = JsonConvert.SerializeObject(myrequest);
    string apiurl = "http://localhost:5000/api/postcsvfile";

    dynamic result = clsCallAPI.put(apiurl, requestData);



my API calling "clsCallAPI" method :-

public static HttpResponseMessage put(string requestUri, string httpContent)
{
    dynamic result = string.Empty;
    HttpWebRequest request = CreateRequest(requestUri, "Put");
    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(httpContent);
    }
    var httpResponse = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    return result;
}


private static HttpWebRequest CreateRequest(string requestUri, string method)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri));
    request.Method = method;
    request.KeepAlive = true;
    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
    request.UseDefaultCredentials = true;
    request.ContentType = "application/json; charset=utf-8";
    request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
    return request;
}


i don't know it is the right way to call an api in which we need to pass .CSV file. can any one suggest me the right solution to do this.

What I have tried:

i tried the all mention code by search on google. but it's not working.
Posted
Updated 24-Sep-22 4:00am
v2
Comments
[no name] 24-Sep-22 11:43am    
This will tell you.

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?source=recommendations&view=aspnetcore-6.0

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