1

I am in asp.net web api. In an API method, I am calling an external web service, that returns XML response. I don't want to deserialize it. I would rather like to send it to the client as is. Initially, I am storing the response in XDocument object but when my client specifies application/xml as accept header, I see the following exception

Type 'System.Xml.Linq.XDeclaration' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

How do I get around this problem

1
  • Could you share how your api method looks like? From the description above i think your object is being trying to be serialized by a formatter which you are not looking for...so would like to see the api method... Commented Sep 5, 2012 at 6:56

1 Answer 1

3

Great Q,i simple write your problem use in api member:

 [HttpGet]
 [ActionName("Books")]
 public HttpResponseMessage MyBook()
    {
        var request = new HttpResponseMessage(HttpStatusCode.OK);
        var doc = XDocument.Parse(@"<books><book><author>MS</author><name>ASP.NET</name></book></books>");
        request.Content = new StringContent(doc.ToString(), Encoding.UTF8, "application/xml");

        return request;
    }

Try this member source.

Sign up to request clarification or add additional context in comments.

4 Comments

I think it would work (not tried) but it wouldn't allow for content negotiation to work. i.e if user specifies application/json in accept header, it would still send xml response, no?
Change to Content request.Content = new StringContent(doc.ToString(), Encoding.UTF8, "application/json"); Headers in Content Type 'application/json'
Or try test this Api member in JS:$.ajax({ url: 'api/Membership/JsonTest', type: 'GET', data: null, dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { alert(JSON.stringify(data)); }, error: function (error) { alert("There was an error posting the data to the server: " + error.responseText); } });
Ok, this solution can be used for time being but Ideally, I would not like to play with content negotiation in API methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.