The length of the string exceeds the value set in the maxJsonLenght property

3

I am sending a picture on Base64 through Ajax, this is because I am using an Apache Cordova PlugIn to take pictures. The result in Base64 is sent to the MVC server in a JsonResult. The problem is that when the string is very long the server returns the error of the title, I have already tried to change the webconfig so that the JavaScriptSerializer accepts more data but without results.

It should be noted that I am receiving data, not sending.

Here is my HTML code.

 function subir(imageData) {

        var x = "data:image/png;base64," + imageData;
        //imageData es la Base64 de la imagen
        $.ajax({
            type: 'POST',
            url: uri,
            data: JSON.stringify({ base64image: x }),
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                alert(data);
            },
            error: function (xhr) {

            }
        });
    }

And my MVC code

[HttpPost]
    public JsonResult GuardarImagenBase64(string base64image)  
    {


        if (string.IsNullOrEmpty(base64image))
            return Json(0);

        var t = base64image.Substring(22);  // remove data:image/png;base64,

        byte[] bytes = Convert.FromBase64String(t);

        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }
        var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + DateTime.Now.Ticks + ".png";
        var fullPath = Path.Combine(Server.MapPath("~/Content/img/"), randomFileName);
        image.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);

        return Json(1);
    }

On my Web.config

  <?xml version="1.0" encoding="utf-8"?>
<!--
  Para obtener más información sobre cómo configurar la aplicación ASP.NET, visite
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"  maxRequestLength="1048576" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="524288000"/>
      </requestFiltering>
    </security>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    //Omití esto pero si tengo mi conexión
  </connectionStrings>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="1073741824"/>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

What do I have to do to make it accept big data? Small images no problem, but because it is a mobile application and usually the photos of the camera are very heavy this always happens.

    
asked by Daisuke Dany 21.06.2018 в 21:01
source

3 answers

0

Ok I could solve it. For this I had to create a modified class that comes by default in Visual Studio that is the JsonValueProviderFactory class.

Inside App_Start create a new class that calls it CustomJsonValueProviderFactory and copy and paste this:

public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
{

    private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
    {
        IDictionary<string, object> d = value as IDictionary<string, object>;
        if (d != null)
        {
            foreach (KeyValuePair<string, object> entry in d)
            {
                AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
            }
            return;
        }

        IList l = value as IList;
        if (l != null)
        {
            for (int i = 0; i < l.Count; i++)
            {
                AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
            }
            return;
        }

        // primitive
        backingStore[prefix] = value;
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        {
            // not JSON request
            return null;
        }

        StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
        string bodyText = reader.ReadToEnd();
        if (String.IsNullOrEmpty(bodyText))
        {
            // no JSON data
            return null;
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength.  This could be read in from the web.config if you prefer
        object jsonData = serializer.DeserializeObject(bodyText);
        return jsonData;
    }

    public override System.Web.Mvc.IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        object jsonData = GetDeserializedObject(controllerContext);
        if (jsonData == null)
        {
            return null;
        }

        Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        AddToBackingStore(backingStore, String.Empty, jsonData);
        return new System.Web.Mvc.DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
    }
}

This class removes the JSON limit and sets it to int32.MaxValue

These are required using:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web.Mvc;
using System.Web.Script.Serialization;

Finally in the Global.asax inside the keys of Application_Start ()

JsonValueProviderFactory jsonValueProviderFactory = null;

        foreach (var factory in ValueProviderFactories.Factories)
        {
            if (factory is JsonValueProviderFactory)
            {
                jsonValueProviderFactory = factory as JsonValueProviderFactory;
            }
        }

        //remove the default JsonVAlueProviderFactory
        if (jsonValueProviderFactory != null) ValueProviderFactories.Factories.Remove(jsonValueProviderFactory);

        //add the custom one
        ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());

It is going to be necessary that in the Global.asax use a Using NombreDeProyecto.App_Start with the reference to your own project, but if you understand what I am saying, use Quick Actions and refactorings.

    
answered by 22.06.2018 / 21:46
source
1

In your Web.Config add the following settings:

<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="1073741824"/>
        <!-- Esto representa 1Gb -->
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

Recommended reading: link

    
answered by 21.06.2018 в 23:10
0

You may be far in excess of the limit that IIS has set by default for the size of requests. Modify your web.config by adding the following

<configuration>
    <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
         <standardEndpoints>           
        <webHttpEndpoint>
     <standardEndpoint name="" helpEnabled="true"automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" /> 
        </webHttpEndpoint>
      </standardEndpoints>
    </system.serviceModel>
    <system.webServer>
            <security>
                <requestFiltering>
                    <requestLimits maxAllowedContentLength=”524288000″/>
                </requestFiltering>
            </security>
    </system.webServer>
  </configuration>

The indicated size maxAllowedContentLength is in bytes.

    
answered by 21.06.2018 в 23:59