Search code examples
jsonxamarinhttpclientxamarin.formssendasync

Xamarin.Forms problems sending large picture over HttpClient SendAsync in Json format


from my Xamarin.Forms app I'm sending a picture and other fields to the server using HttpClient in Json format. If I send a little picture I've got with my front camera it's working fine, if I send a larger picture I've got with the rear camera it doesn't work and I always get an exception: "Excepional error".

I tried to create the same code in a windows form application and it's working fine also with large images, but not from my App.

I have already modified on the server web.config to increase json content size:

<jsonSerialization maxJsonLength="50000000"/>

Can someone help ?! Thanks!!

This is the code on my app:

public async static Task<MyAppDataModels.Common.WsResponse> PostPhotoFromUser(int catalogItemId, int objReferenceId, int languageId, byte[] fileContent)
    {
        MyAppDataModels.Common.WsResponse MyResponse = new MyAppDataModels.Common.WsResponse();
        try
        {                
            HttpClient MyHttpClient = new HttpClient();
            MyHttpClient.Timeout = TimeSpan.FromSeconds(520);
            MyHttpClient.BaseAddress = new Uri(string.Format("{0}/Application/ApplicationPostPhotoFromUser", MyAppSettings.ServerApiUrl));
            MyHttpClient.DefaultRequestHeaders.Accept.Clear();
            MyHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            MyHttpClient.DefaultRequestHeaders.AcceptCharset.Clear();
            MyHttpClient.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
            HttpRequestMessage MyWsRequest = new HttpRequestMessage(HttpMethod.Post, MyHttpClient.BaseAddress);

            dynamic MyObjData = new JObject();
            MyObjData["CatalogItemId"] = catalogItemId;
            MyObjData["ObjReferenceId"] = objReferenceId;
            MyObjData["UserId"] = string.Empty;
            MyObjData["LanguageId"] = languageId;
            MyObjData["Picture"] = fileContent;

            string MySerializedPostedData = JsonConvert.SerializeObject(MyObjData);
            MyWsRequest.Content = new StringContent(MySerializedPostedData, Encoding.UTF8, "application/json");

            HttpResponseMessage MyWsResponse = await MyHttpClient.SendAsync(MyWsRequest, HttpCompletionOption.ResponseHeadersRead);
            MyWsResponse.EnsureSuccessStatusCode();
            var MyContentResponse = await MyWsResponse.Content.ReadAsStringAsync();
            MyResponse.ResponseId = MyAppConstants.Constants.ResponseCode.Successfull;
        }
        catch (Exception ex)
        {
            MyResponse.ResponseId = MyAppConstants.Constants.ResponseCode.ErrorWhileProcessingRequest;
            MyResponse.ResponseErrorMessage = ex.Message;
        }
        return MyResponse;
    }

Solution

  • From the stacktrace,

    System.Net.WebExceptionStatus.ProtocolError

    means that the server responded with some 40x error, maybe 401 (Acess Denied) or something similar.

    you can wrap your call in a:

    try
    {
    }
    catch(WebException ex){
    }
    

    then check the exceptions Status and cast the exception's response like that:

    ((HttpWebResponse)e.Response).StatusDescription
    

    to get more info about what has gone wrong on the server.

    EDIT: Because you're uploading large files, you can resolve the "maximum request length exceeded exception", you need to modify your server's (ASP.NET for example) web.config file to accept large request size:

    <configuration>
        <system.web>
            <httpRuntime maxRequestLength="50000" />
        </system.web>
    </configuration>