Posts Tagged ‘HTTP’

Uploading a File in ASP.Net Web API

Consider the following model file and a sample POST method.

namespace FeedbackService.Models
    public class Feedback
        public string Id { get; set; }
        public string EmailId { get; set; }
        public string Comment { get; set; }
        public string PageUrl { get; set; }
        public byte[] Attachment { get; set; }

The corresponding “Post” method is as given below.

        public HttpResponseMessage Post([FromBody] Feedback value)
                return ModelState.IsValid ? Request.CreateResponse(_wrapper.CreateFeedback(value) ? HttpStatusCode.Created : HttpStatusCode.InternalServerError, value) : Request.CreateResponse(HttpStatusCode.BadRequest, value);
            catch (Exception ex)
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);

In the above scenario, the file to be uploaded is converted to byte array first and then this request was posted from an html page. The first issue we encountered was “Maximum content length exceeded” and to troubleshoot this issue, we have to add the following entries in “web.config”

<!-- To be added under <system.web> -->
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" executionTimeout="3600" />

<!-- To be added under <system.webServer> -->
<requestLimits maxAllowedContentLength="1073741824" />

The above said error went off, but there was new issue wherein the file upload was taking more time, That’s when we tried doing this the other way, we modified the “POST” method to include the following:

       public HttpResponseMessage Post()
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

                var httpRequest = HttpContext.Current.Request;

                // Check if any file(s) have been uploaded
                if (httpRequest.Files.Count > 0)
                    // Get file content as byte array
                    MemoryStream ms = new MemoryStream();
                    byte[] fileContent = ms.ToArray();

                    // Populate Feedback object
                    Feedback feedback = new Feedback();
                    feedback.PrototypeId = httpRequest.Form["prototypeId"];
                    feedback.PageUrl = httpRequest.Form["pageURL"];
                    feedback.EmailId = httpRequest.Form["emailId"];
                    feedback.Comment = httpRequest.Form["comment"];
                    feedback.Attachment = fileContent;

                    // Call the wrapper method
                    if (_wrapper.CreateFeedback(feedback))
                        return Request.CreateResponse(HttpStatusCode.Created);
                    return Request.CreateResponse(HttpStatusCode.BadRequest);

                // Return status indicating that the server refuses to fulfill request
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            catch (Exception ex)
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);

and to test this, we created the following sample html file

<!DOCTYPE html>
<html xmlns="">
    <title>Feedback Test Form</title>
    <style type="text/css">
            table.bottomBorder {
                border-collapse: collapse;
            table.bottomBorder td, table.bottomBorder th {
                border-bottom: 1px dotted black;
                padding: 5px;
    <form enctype="multipart/form-data" method="post" action="http://localhost:62465/api/feedback" id="feedbackForm" novalidate="novalidate">
            <legend><b>Submit Feedback</b></legend>
            <table class="bottomBorder">
                    <td>Prototype ID:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="prototypeId" id="prototypeId" value="59938fe1-d80a-4534-8a7a-01977dab8370"></td>
                    <td>Page URL:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="pageURL" id="pageURL" value="http://localhost:62465/PostFeedback.html"></td>
                    <td>Email ID:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="emailId" id="emailId" value=""></td>
                    <td><textarea name="comment" style="width: 320px; color: grey;" cols="30" rows="4">This page is super awesome!</textarea></td>
                    <td>File Attachment:</td>
                    <td><input type="file" style="width: 320px; color: grey;" name="fileAttachment" id="fileAttachment"></td>
                <input type="submit" value="Submit Feedback" id="btnUpload">

The above is just a sample implementation of uploading a file in ASP.Net Web API as well as an example of sending HTML form data.

Categories: ASP.NET, C# Tags: , , , , , ,
%d bloggers like this: