Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post file as well as some parameter to web api

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

like image 594
User1710 Avatar asked Jun 14 '16 07:06

User1710


People also ask

How do I write a post in Web API?

The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework. The action method that will handle HTTP POST request must start with a word Post.


1 Answers

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>();
        }
    }
like image 102
poppertech Avatar answered Oct 03 '22 06:10

poppertech