8

I am trying to use N-UNIT to test my web API application but I am unable to find a proper way to test my file upload method. Which would be the best approach to test the method?

Web API Controller:

[AcceptVerbs("post")]
public async Task<HttpResponseMessage> Validate()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request");
        }
        var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing 
        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            foreach (var item in provider.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    Stream stream = item.ReadAsStreamAsync().Result;
        // do some stuff and return response
                    resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml"
                    return resp;
                }
            }
               return resp;
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

2 Answers 2

21

Based on your above comment, following is an example:

HttpClient client = new HttpClient();

MultipartFormDataContent formDataContent = new MultipartFormDataContent();
formDataContent.Add(new StringContent("Hello World!"),name: "greeting");
StreamContent file1 = new StreamContent(File.OpenRead(@"C:\Images\Image1.jpeg"));
file1.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file1.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file1);
StreamContent file2 = new StreamContent(File.OpenRead(@"C:\Images\Image2.jpeg"));
file2.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file2.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file2);

HttpResponseMessage response = client.PostAsync("http://loclhost:9095/api/fileuploads", formDataContent).Result;

The request over the wire would like:

POST http://localhost:9095/api/fileuploads HTTP/1.1
Content-Type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f"
Host: localhost:9095
Content-Length: 486
Expect: 100-continue
Connection: Keep-Alive

--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=greeting

Hello World!
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image1.jpeg

----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image2.jpeg

----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f--
1
  • I was looking for a simple solution this can complicate a lot things
    – Muhammad
    Commented Jul 22, 2013 at 13:59
4

After spending a bit of time looking into WebClient I was able to come up with this:

     try
        {
            var imageFile = Path.Combine("dir", "fileName");
            WebClient webClient = new WebClient();
            byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
            Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
            Console.WriteLine("File Upload was successful"); 
        }
        catch (WebException wexc)
        {
           Console.WriteLine("Failed with an exception of " + wexc.Message);  
           // anything other than 200 will trigger the WebException

        }
2
  • why not use HttpClient from System.Net.Http?
    – Kiran
    Commented Jul 18, 2013 at 20:17
  • I don't think HttpClient has a upload file designed specifically for file uploading.
    – Muhammad
    Commented Jul 18, 2013 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.