ASP.NET WebMethod Returns JSON wrapped in quotes

前端 未结 3 1438
挽巷
挽巷 2020-12-15 00:53

I have an asp.net page with a WebMethod on it to pass JSON back to my javascript.

Bellow is the web method:

[WebMethod]
public static string getData         


        
3条回答
  •  孤街浪徒
    2020-12-15 01:44

    I had a similar issue with my code. I was trying to return an XmlDocument as JSON to a calling script but returning XmlDocument from the WebService returned an empty set of arrays (as XmlDocument is NOT serializable!).

    If i set the ScriptService with the attribute ResponseFormat.JSON then my JSON was double-escaped.

    The way to out-fox ASP.NET is to tell ASP.NET that you're returning XML and then it won't double-escape your JSON ;-)

        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public String MyJSONWebService(String sParam1, String sParam2, String sParam3)
        {
           ... do stuff.....
           XmlDocument oXMLDocument = new XmlDocument();
           oXMLDocument.LoadXml(sXML);
           sJSON = JsonConvert.SerializeXmlNode(oXMLDocument.SelectSingleNode("autnresponse"));
           return sJSON;
        }
    

    I know it's a hack but .....

提交回复
热议问题