0
votes

Background

I currently have working C# code to read the values in a HTTP POST form submission from a webpage. It looks like this:

public class CompanyDTO
{
    public string CompanyName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }
}

// POST: api/Submission
public HttpResponseMessage Post(CompanyDTO Company)
{
    return JsonToBrowser("{'location':'" + Company.City + "," + Company.State + "'}");
}

I also have working code to read attachments from a file upload control on a page:

// POST: api/Submission
public HttpResponseMessage Post()
{
    // Process and save attachments/uploaded files
    var folderName = "App_Data";
    var PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
    var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
    if (Request.Content.IsMimeMultipartContent())
    {
        var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
        var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }

            var fileInfo = streamProvider.FileData.Select(i =>
            {
                var info = new FileInfo(i.LocalFileName);
                return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
            });
            return fileInfo;
        });

        return JsonToBrowser("{'status':'success'}");
    } 
    else 
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
    }
}

Obviously there is a bit more to the last piece of code, but I hope it at least illustrate my issue.

My problem

I am now trying to combine these two pieces of code. I thought it would be as easy as putting the data transfer object in the Post function:

public HttpResponseMessage Post(CompanyDTO Company)

This results in the following being returned to the browser when I perform the HTTP POST:

{ "Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.", "ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'CompanyDTO' from content with media type 'multipart/form-data'.", "ExceptionType":"System.Net.Http.UnsupportedMediaTypeException", "StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }

My Question

So how do I both upload one or more files and read/process the regular form data fields using C# and ASP.NET. I am using Visual Studio 2013 (Community Edition). Also, I am a beginner in C#, so I may need some extra hints/help if you refer to a function/class about where to find it.

The closest SO question I found related to this issue is How to submit form-data with optional file data in asp.net web api but it does not have any response/answer...

1

1 Answers

1
votes

Here's my solution when I encountered this issue:

Client:

 public async Task UploadImage(byte[] image, string url)
        {
            Stream stream = new System.IO.MemoryStream(image);
            HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());

            Uri resourceAddress = null;
            Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
            request.Content = streamContent;

            var httpClient = new Windows.Web.Http.HttpClient();
            var cts = new CancellationTokenSource();
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
        }

Controller:

public async Task<HttpResponseMessage> Post()
{
    Stream requestStream = await this.Request.Content.ReadAsStreamAsync();
    byte[] byteArray = null;
    using (MemoryStream ms = new MemoryStream())
    {
        await requestStream.CopyToAsync(ms);
        byteArray = ms.ToArray();
    }
    .
    .
    .
    return Request.CreateResponse(HttpStatusCode.OK);
}