Post file as well as some parameter to web api

19,869

I was able to post successfully with the following console application (based on this post):

    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:3963/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string filepath = "C:/Users/Popper/Desktop/Stackoverflow/MatchPositions.PNG";
            string filename = "MatchPositions.PNG";

            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
            content.Add(fileContent);

            HttpResponseMessage response = await client.PostAsync("api/Upload?participantsId=2&taskId=77&EnteredAnswerOptionId=235", content);
            string returnString = await response.Content.ReadAsAsync<string>();
        }
    }
Share:
19,869
User1710
Author by

User1710

Updated on June 15, 2022

Comments

  • User1710
    User1710 almost 2 years

    I have Web api controller Uploads Controller which have PostUpload method to store data to database.

    Now I'm trying to post file and some parameter to that web api but all try are fail like pass by array list ,json object ,we can't post file and parameter to web api?

    var request = new RestRequest("Uploads", Method.POST);
    request.RequestFormat = DataFormat.Json;
    
    request.AddHeader("Content-Type", "application/json");
    request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
    request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
    request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
    request.AddParameter("participantsId", 2);
    request.AddParameter("taskId", 77);
    request.AddParameter("EnteredAnswerOptionId", 235);
    IRestResponse response = createClient().Execute(request);
    

    web api method:

    [HttpPost]
    public string PostUpload(int? participantsId, int? taskId, int? EnteredAnswerOptionId)
    {
        var file = HttpContext.Current.Request.Files.Count > 0 ?
        HttpContext.Current.Request.Files[0] : null;
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(HttpContext.Current.Server.MapPath("~/uploads"), fileName);
            file.SaveAs(path); 
        }
        return "/uploads/" + file.FileName;
    }
    

    but it give error like:

    ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'xxxx' from content with media type 'multipart/form-data

    I need to post file as well as parameter to my api.

    sending data using restsharp