ASMX WebMethod配置返回JSON却返回XML的问题求助
解决ASMX WebMethod返回XML而非JSON的问题
我来帮你搞定这个头疼的问题——明明在WebMethod里指定了返回JSON,结果Angular拿到的却是XML,设成json类型还报错。咱们一步步排查修复:
1. 先检查Web.config的配置
ASMX要正确返回JSON,得在Web.config里做必要的配置,确保服务器支持JSON序列化和HTTP GET请求:
在<system.web>节点下添加或确认这段配置:
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> <jsonSerialization maxJsonLength="50000000"/> </webServices>
另外,在<system.webServer>的<handlers>里确认有以下处理程序(没有的话加上):
<handlers> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.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=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </handlers>
2. 调整WebMethod的ScriptMethod属性
给你的ScriptMethod加上XmlSerializeString = false,强制服务器用JSON序列化返回对象,而不是 fallback 到XML:
[WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)] public MyProjects getReport(int reportId) { // 你的业务逻辑代码 }
3. 修改Angular的请求,明确要求JSON
Angular的请求要告诉服务器“我要JSON格式的响应”,所以要添加Accept: application/json请求头,同时把responseType改回json:
import { HttpClient, HttpHeaders } from '@angular/common/http'; // 注入HttpClient到你的组件或服务中 constructor(private http: HttpClient) {} // 调用WebService的方法 fetchReport() { const requestHeaders = new HttpHeaders({ 'Accept': 'application/json' }); this.http.get('http://localhost:51071/webservice1.asmx/getReport?reportId=596', { withCredentials: true, headers: requestHeaders, responseType: 'json' }) .subscribe( (data) => console.log('拿到JSON数据:', data), (error) => console.error('请求出错:', error) ); }
额外排查小贴士
- 确认你的
MyProjects类是可序列化的:所有属性都是公共的,没有循环引用(循环引用会导致JSON序列化失败,服务器会自动转成XML返回) - 如果上面的方法都不行,可以试试兜底方案:把WebMethod的返回类型改成
string,手动序列化对象:
[WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public string getReport(int reportId) { MyProjects result = // 你的业务逻辑生成的对象 var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return serializer.Serialize(result); }
内容的提问来源于stack exchange,提问作者Sandeep Thomas
相关产品推荐
相关产品推荐

