Error using MvxMultiPartFormRestRequest to post image/data to API controller

170 views Asked by At

I am building an Android app which has a form that user can post image for an item. So the post data is an int field and an image.

I use MvvmCross Network plugin to post and got below error. I am a beginner and I do not know where I did wrong: mobile app code or API controller code?

error = {System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
  at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in <filename unknown>:0 
  at System.Net.HttpWebRequest.SetResponseData ...

This is mobile app code:

This is select image code:

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
            _imgUri = data.Data;

            _imgPath = GetPathToImage(_imgUri);
            _contentType = ContentResolver.GetType(_imgUri);
        }
    }

Then click Submit button

    private void btnSubmit_Click(object sender, EventArgs e)
    {
        MemoryStream stream = new MemoryStream();
        ContentResolver.OpenInputStream(_imgUri).CopyTo(stream);
        _vm.Submit(_imgPath, _contentType, stream);
    }

This is Submit function:

public void Submit(string fileName, string contentType, MemoryStream stream) {
    //Post data
    int itemId = 1;

    List<MvxMultiPartFormRestRequest.IStreamForUpload> streams = new List<MvxMultiPartFormRestRequest.IStreamForUpload>();
    streams.Add(new MvxMultiPartFormRestRequest.MemoryStreamForUpload("userFile", fileName, contentType, stream)); 

    var client = Mvx.Resolve<IMvxJsonRestClient>();
    var r = new MvxMultiPartFormRestRequest("https://.../api/ItemUserImage");

    r.FieldsToSend.Add("itemId", itemId.ToString());
    r.StreamsToSend.AddRange(streams);

    client.MakeRequestFor<MyResponse>(r, (result) =>
    {
         Mvx.Resolve<IUserInteraction>().Alert(result.Result.ResponseText, null, TitleInformation);
    }, (error) =>
    {
        //I met error here
    });

This is my API controller:

public class ItemUserImageController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        Response response = new Response();
        response.ResponseCode = 1;
        response.ResponseText = "step0-";

        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            response.ResponseText += "step1-";
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        response.ResponseText += "step2-";

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

        response.ResponseText += "step3-";
        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            response.ResponseText += "step4-";
            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    response.ResponseText += string.Format("{0}: {1}-", key, val);
                }
            }

            response.ResponseText += "step5-";
            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                response.ResponseText += string.Format("{0} - Server file path: {1}-", file.Headers.ContentDisposition.FileName, file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK, response);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, response.ResponseText ,e);
        }
    }            
}

Please help. Thank you.

1

There are 1 answers

0
Stuart On

This "bug" could be lots of things. Really the best way to resolve it is to get in there with some debugging tools, to set breakpoints in both the client and the ASP.Net app and to see what the communication is.

Once you start debugging this, I'm sure you'll quickly

Beyond that, the only "spider sense tingle" I got looking through your client code was a slight concern that you might need to reset the current position in your MemoryStream back to the start (but I haven't thought this fully through).