4

Preparing ASP.NET for Long JSON Requests

 2 years ago
source link: https://www.textcontrol.com/blog/2021/05/20/preparing-asp-net-for-long-json-requests/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Preparing ASP.NET for Long JSON Requests

The ASP.NET MVC DocumentViewer uses an ASP.NET controller to manage incoming client requests using JSON. The default JSON size of 4MB can be too small for handling larger files. This article shows how to replace the default JavaScriptSerializer with Json.NET.

In your ASP.NET Web Application, install the popular and de-facto standard Newtonsoft.Json:

Install-Package Newtonsoft.Json

Then create a class JsonDotNetValueProviderFactory derived from ValueProviderFactory:

public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory { public override IValueProvider GetValueProvider(ControllerContext controllerContext) { if (controllerContext == null) throw new ArgumentNullException("controllerContext");

if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return null;

var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream); var bodyText = reader.ReadToEnd();

return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>( JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture); } }

In the Global.asax.cs file of your ASP.NET application, add the following code:

ValueProviderFactories.Factories.Remove( ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());

ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());

This code removes existing JsonValueProviderFactory objects and activates the newly created factory.

The complete Global.asax.cs of a new project should look like this:

public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles);

ValueProviderFactories.Factories.Remove( ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());

ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory()); } }

After this change, the ASP.NET controllers use Json.NET to deserialize incoming payloads and can handle unlimited file sizes loaded into the DocumentViewer.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK