简体   繁体   中英

Return custom XML from Web Api HttpRequestMessage.CreateResponse

I need to return xml from my mvc 4 web api, it should look like this:

<?xml version="1.0" encoding="UTF-8" ?>
<response>
     <success/>
</response>

My code currently looks like this:

Request.CreateResponse<string>(HttpStatusCode.OK, "success", Configuration.Formatters.XmlFormatter);

And the xml it returns looks like this, which doesn't meet the client's requirements:

<string>success</string>

Is there a way to achieve my desired result? Thank you!

Try defining a Reponse class and have your web api return a CreateResponse<Response> instead:

[System.Xml.Serialization.XmlRootAttribute(ElementName="response")]
public class Response
{
    [System.Xml.Serialization.XmlElement(IsNullable = true)]
    public string success { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM