Serialization asp.net web api中特定类型的自定义Xml序列化程序

Serialization asp.net web api中特定类型的自定义Xml序列化程序,serialization,xml-serialization,asp.net-web-api,.net-4.5,Serialization,Xml Serialization,Asp.net Web Api,.net 4.5,我在asp.NETWebAPI中。在API方法中,我调用一个外部web服务,该服务返回XML响应。我不想反序列化它。我宁愿按原样发送给客户。最初,我将响应存储在XDocument对象中,但是当我的客户机将application/xml指定为accept头时,我看到以下异常 Type 'System.Xml.Linq.XDeclaration' cannot be serialized. Consider marking it with the DataContractAttribute attr

我在asp.NETWebAPI中。在API方法中,我调用一个外部web服务,该服务返回XML响应。我不想反序列化它。我宁愿按原样发送给客户。最初,我将响应存储在
XDocument
对象中,但是当我的客户机将
application/xml
指定为accept头时,我看到以下异常

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.

我该如何解决这个问题呢

太好了,我简单地把你的问题写在api成员中:

 [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;
    }
[HttpGet]
[行动名称(“书籍”)]
公共HTTPResponseMessageMyBook()
{
var请求=新的HttpResponseMessage(HttpStatusCode.OK);
var doc=XDocument.Parse(@“MSASP.NET”);
request.Content=newstringcontent(doc.ToString(),Encoding.UTF8,“application/xml”);
返回请求;
}

尝试此成员源。

您应该能够使用某些特定于控制器的设置。请参见示例

能否分享您的api方法?从上面的描述中,我认为您的对象正在尝试由一个格式化程序进行序列化,而您不需要这个格式化程序…因此希望看到api方法…我认为它可以工作(未尝试),但它不允许内容协商工作。i、 e如果用户在accept头中指定了
application/json
,它仍然会发送xml响应,不更改内容
request.Content=new-StringContent(doc.ToString(),Encoding.UTF8,“application/json”)内容类型“application/json”中的标题,或尝试在JS:
$.ajax中测试此Api成员({url:'Api/Membership/JsonTest',类型:'GET',数据:null,数据类型:“json”,内容类型:“application/json;charset=utf-8”,成功:函数(数据){alert(json.stringify(data));},error:function(error){alert(“将数据发布到服务器时出错:“+error.responseText”);})好的,这个解决方案暂时可以使用,但理想情况下,我不想在API方法中使用内容协商。尽管使用了特定于控制器的属性,但我正在寻找一种方法来更改特定类型的xml序列化程序。所以,如果同一时间出现在多个控制器中,它将由该序列化程序处理。