VB.NET传含61个base64文件的JObject时C# WebAPI的dynamic参数为null
解决方案:VB.NET调用C# WebAPI传递大量Base64文件时dynamic参数为null问题
该问题由ASP.NET Web API默认的请求长度、JSON序列化限制触发,导致超量请求体解析失败,最终参数绑定为null,可按以下步骤修复:
1. 调整Web.config请求大小限制
修改Web.config配置,放开请求长度上限:
<!-- system.web节点下配置,maxRequestLength单位为KB,示例为100MB --> <system.web> <httpRuntime targetFramework="4.5" maxRequestLength="102400" /> </system.web> <!-- system.webServer节点下配置,maxAllowedContentLength单位为字节,示例为100MB --> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="104857600" /> </requestFiltering> </security> </system.webServer>
注意两个配置的单位不同,需要保持数值匹配
2. 放开JSON序列化长度限制
在App_Start/WebApiConfig.cs的Register方法中,修改Newtonsoft.Json序列化配置,放开数组、字符串长度限制:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 原有路由配置保留,新增以下序列化配置 config.Formatters.JsonFormatter.SerializerSettings.MaxArrayLength = int.MaxValue; config.Formatters.JsonFormatter.SerializerSettings.MaxStringContentLength = int.MaxValue; config.Formatters.JsonFormatter.SerializerSettings.MaxDepth = 64; } }
3. (推荐)替换dynamic为强类型参数接收
强类型参数绑定的容错性高于dynamic,可进一步降低解析失败概率,先定义接收DTO类:
public class UploadRequestDto { public string Field1 { get; set; } public string Field2 { get; set; } public List<string> ListFileFotoBase64 { get; set; } }
修改接口参数声明:
[Route("WebApiMethod")] [ResponseType(typeof(HttpResponseCustom))] [HttpPost] public IHttpActionResult WebApiMethod(UploadRequestDto value) { try { // 直接读取属性即可,无需手动转换JArray List<string> ListFileFotoBase64 = value.ListFileFotoBase64; // 原有业务逻辑保留 } }
4. 可选验证步骤
如果修改后仍存在问题,可在VB.NET端打印jObj.ToString()的长度,配合Fiddler抓包确认请求体是否完整发送,排除客户端请求截断问题。
内容的提问来源于stack exchange,提问作者DrViente
相关产品推荐
相关产品推荐

