Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpPost and webapi

I have created an API which takes a file as input and processes it. The sample is like this...

[HttpPost]
    public string ProfileImagePost(HttpPostedFile HttpFile)
    {

      //rest of the code
     }

Then I have creted a Client to consume this as follows...

 string path = @"abc.csv";
        FileStream rdr = new FileStream(path, FileMode.Open, FileAccess.Read);
        byte[] inData = new byte[rdr.Length];
        rdr.Read(inData, 0, Convert.ToInt32(rdr.Length));

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/abc/../ProfileImagePost");
        req.KeepAlive = false;
        req.ContentType = "multipart/form-data"; 
        req.Method = "POST";
        req.ContentLength = rdr.Length;
        req.AllowWriteStreamBuffering = true;

        Stream reqStream = req.GetRequestStream();

        reqStream.Write(inData, 0, Convert.ToInt32(rdr.Length));
        reqStream.Close();
        HttpWebResponse TheResponse = (HttpWebResponse)req.GetResponse();
        string TheResponseString1 = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd();
        TheResponse.Close();

But I get 500 error at on client side. Help me out of it guys.

Thanx in advance...

like image 651
user1871770 Avatar asked Nov 21 '25 12:11

user1871770


1 Answers

The ASP.NET Web API doesn't work with HttpPostedFile. Instead you should use a MultipartFormDataStreamProvider as shown in the following tutorial.

Also your client side call is wrong. You have set the ContentType to multipart/form-data but you are not respecting this encoding at all. You are simply writing the file to the request stream.

So let's take an example:

public class UploadController : ApiController
{
    public Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HostingEnvironment.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        // Read the form data
        return Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
        {
            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }, TaskScheduler.FromCurrentSynchronizationContext());
    }
}

and then you could use an HttpClient to call this API:

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;

class Program
{
    static void Main(string[] args)
    {
        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            client.BaseAddress = new Uri("http://localhost:16724/");
            var fileContent = new ByteArrayContent(File.ReadAllBytes(@"c:\work\foo.txt"));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Foo.txt"
            };
            content.Add(fileContent);
            var result = client.PostAsync("/api/upload", content).Result;
            Console.WriteLine(result.StatusCode);
        }
    }
}
like image 92
Darin Dimitrov Avatar answered Nov 23 '25 03:11

Darin Dimitrov