ASP.Net WEB API 无法 POST 来自移动设备的大型 JSON 数据

Posted

技术标签:

【中文标题】ASP.Net WEB API 无法 POST 来自移动设备的大型 JSON 数据【英文标题】:ASP.Net WEB API Failing POST Large JSON data from Mobile 【发布时间】:2019-12-02 02:18:03 【问题描述】:

我正在使用 Mobile 的 ASP.net WEB api。每次都失败。我收到此错误。

Error during serialization or deserialization using the JSON javascriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

我已经在 Webconfig 上添加了 maxJsonLength

    <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
  </system.webServer>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644"/>
      </webServices>
    </scripting>
  </system.web.extensions>

这是我的控制器,我如何在 postDataForSync 方法中获取 JSON? 现在它在构造方法之后崩溃了。

 public class MobileAPIController : Controller

    JavaScriptSerializer serializer;
    public MobileAPIController() 

        serializer = new JavaScriptSerializer();
        serializer.MaxJsonLength = Int32.MaxValue;

    


    //
    //GET : MobileAPI/login

    public object login(string userId, string password)
     
    

    //
    //GET : MobileAPI/getDataForSync
    public object getDataForSync(string userId) 

    

    //
    //POST : MobileAPI/postDataForSync
    [HttpPost]
    public object postDataForSync(string syncData_)
    
    

错误,

[ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input]
   System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +168
   System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +211
   System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +16
   System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +69
   System.Web.Mvc.ControllerBase.get_ValueProvider() +30
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +62
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.&lt;BeginExecute&gt;b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +159
</pre>
                        </code>
                    </td>
                </tr>
            </table>
            <br>
            <hr width=100% size=1 color=silver>
            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3062.0

谢谢。

【问题讨论】:

【参考方案1】:

我是这样用我的方法的

上一个方法

[HttpPost]
public object postDataForSync(string syncData_)


更新方法

[HttpPost]
public object postDataForSync()

 Stream req = Request.InputStream;
 req.Seek(0, System.IO.SeekOrigin.Begin);
 string json = new StreamReader(req).ReadToEnd();
 MyModel model = JsonConvert.DeserializeObject<MyModel>(json);

这个 SO Answer 帮助我解决了这个问题。 - SO

【讨论】:

【参考方案2】:

您是否尝试在 Web 配置的 appsetting 下添加 MaxJsonDeserializerMembers?像这样,至少对我有用

  <appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="1500000" />
  </appSettings>

【讨论】:

以上是关于ASP.Net WEB API 无法 POST 来自移动设备的大型 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST

无法使用javascript向ASP.NET web api Controller发送http POST请求

ASP.NET Web API - 模型绑定不适用于 POST 上的 XML 数据

如何在目标c中的asp.net web api方法中使用POST方法?

ASP.Net Web Api Core - 无法在抽象基类中使用 CreatedAtRoute

无法使用 Windows 身份验证发布到 asp.net core web api