7

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
User1710
  • 191
  • 1
  • 4
  • 19

1 Answers1

5

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>();
        }
    }
Community
  • 1
  • 1
poppertech
  • 1,286
  • 2
  • 9
  • 17
  • 1
    Thanks for replay.Actually my issue get resolve yesterday.The problem is that I am sending file of type multipart/data and with parameter as json so at web API it reject to convert getting as above mention error. So I send File by using AddFile() method and Sent paramenter using request.AddQueryParameter() method.I think your answer is also correct.Thanks once again. – User1710 Jun 15 '16 at 10:47
  • 1
    This doesn't work for me I get `StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'`. My file could be anything, word, pdf, image or text etc – djack109 Apr 23 '20 at 18:11