Asp.net
jQuery Ajax 到 asp.net asmx web 服務拋出請求格式無效:application/json
我讓 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> </httpModules> <compilation debug="true" strict="true" explicit="true" targetFramework="4.0"> </compilation> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"> </pages> <authentication mode="Forms"> <httpHandlers> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules> </modules> <handlers> </handlers> <httpErrors errorMode="Custom" > </httpErrors> </system.webServer> </configuration>
DOH,我在錯誤的 web.config 中工作。
就像很多關於 SO 的問題一樣,解決方案是添加以下內容。
<system.webServer> <handlers> <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" /> <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" /> </handlers> </system.webServer>