How do I return pure XML from asmx web service?

2020-06-04 15:09发布

问题:

I want an asmx webservice with a method GetPeople() that returns the following XML (NOT a SOAP response):

<People>

    <Person>
        <FirstName>Sara</FirstName>
        <LastName>Smith</LastName>
    </Person>

    <Person>
        <FirstName>Bill</FirstName>
        <LastName>Wilson</LastName>
    </Person>

</People>

How can I do this?

回答1:

Look at using the [ScriptMethod] attribute.



回答2:

If you don't want the Response to be in a SOAP envelope, are you also not bothered about calling the web service using SOAP. e.g. you are not creating proxy classes web references etc and just using http post or get to call the web service?

If so rather than writing a web service, write a ASHX handler file. You can then simply set the Response.ContentType to text/xml and do Response.Write(XmlDocument.ToString()). That will return pure unadulaterated XML plus the relevent http headers.



回答3:

I see I can set the return type of the method to XmlDocument. This seems to work.

[WebMethod]
public XmlDocument ReturnXml()
{
    XmlDocument dom = new XmlDocument();

    XmlElement people = dom.CreateElement("People");
    dom.AppendChild(people);

    XmlElement person = dom.CreateElement("Person");
    people.AppendChild(person);

    XmlElement firstName = dom.CreateElement("FirstName");
    person.AppendChild(firstName);

    XmlText text = dom.CreateTextNode("Bob");
    firstName.AppendChild(text);



    // load some XML ...
    return dom;
}


回答4:

You may use Soap Extensions to create / customize for your needs.