Asp.net

jQuery Ajax 到 asp.net asmx web 服務拋出請求格式無效:application/json

  • May 31, 2013

我讓 jquery 呼叫一個帶有整數的 asp.net webservice。在我們移植到 .net 4.0 的舊版應用程序上,我無法讓這個呼叫正常工作。我可以呼叫一個沒有參數的方法,但是向 Web 方法發送數據會返回以下錯誤:

System.InvalidOperationException: Request format is invalid: application/json; charset=UTF-8. 
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() 
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

我在一個空白項目中創建了完全相同的程式碼,並且執行良好。我在 web.config 中看不到空白項目添加的任何會產生影響的內容。

jQuery程式碼

$.ajax({
   type: "POST",
   url: "/WebService1.asmx/Test",
   data: JSON.stringify({"code": 1234}),
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (msg) {
       alert(msg);
   }
});

我的網路服務程式碼

<ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService1
   Inherits WebService

   <WebMethod()>
   Public Function Test(ByVal code As Integer) As String
       Return "success"
   End Function

   <WebMethod()>
   Public Function Hello() As String
       Return "hello"
   End Function    
End Class

網頁配置

<?xml version="1.0" encoding="UTF-8"?>
<configuration>  
   <appSettings>
   </appSettings>
   <connectionStrings>
   </connectionStrings>
   <system.web>
       <httpRuntime enableVersionHeader="false" />
       <httpCookies httpOnlyCookies="true" requireSSL="false" lockItem="true" />
       <trace enabled="false" pageOutput="true" requestLimit="40" localOnly="true"/>

       <httpModules>
       &lt;/httpModules&gt;
       &lt;compilation debug="true" strict="true" explicit="true" targetFramework="4.0"&gt;

       &lt;/compilation&gt;
       &lt;pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"&gt;
       &lt;/pages&gt;

       &lt;authentication mode="Forms"&gt;

       <httpHandlers>     
       &lt;/httpHandlers&gt;
   &lt;/system.web&gt;

   &lt;system.webServer&gt;

   &lt;validation validateIntegratedModeConfiguration="false" /&gt;
   &lt;modules&gt;
   &lt;/modules&gt;
   &lt;handlers&gt;
   &lt;/handlers&gt;
   &lt;httpErrors errorMode="Custom" &gt; 
   &lt;/httpErrors&gt;
   &lt;/system.webServer&gt;
&lt;/configuration&gt;

DOH,我在錯誤的 web.config 中工作。

就像很多關於 SO 的問題一樣,解決方案是添加以下內容。

&lt;system.webServer&gt;
       &lt;handlers&gt;
           &lt;add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt;
           &lt;add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt;
       &lt;/handlers&gt;
 &lt;/system.webServer&gt;

引用自:https://stackoverflow.com/questions/11992139