当我将使用泛型类型的返回对象序列化为XML时,我的REST API出现了错误。但是,当使用JSON时,此错误不会重现。
以下是一个简化的示例,演示了我的问题:
using System;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web.Http;
namespace Areas.API
{
public abstract class AnimalController<TProperties> : ApiController
where TProperties : new()
{
protected abstract TProperties makeNew( Int32 Id );
[Route( "{id}" )]
public AnimalReturn<TProperties> Get( Int32 id )
{
TProperties p = makeNew( id );
return new AnimalReturn<TProperties>()
{
Properties = p,
Request = Request,
StatusCode = HttpStatusCode.OK
};
}
}
public class AnimalReturn<TProperties> : AnimalResult
{
public TProperties Properties;
}
public class AnimalResult : IHttpActionResult
{
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
public Task<HttpResponseMessage> ExecuteAsync( System.Threading.CancellationToken cancellationToken )
{
HttpResponseMessage response = null;
if( null != Request )
{
response = Request.CreateResponse( StatusCode, this );
}
return Task.FromResult( response );
} // ExecuteAsync()
}
[RoutePrefix( "api/v3/Fish" )]
public class FishController : AnimalController<FishController.FishProperties>
{
public class FishProperties
{
public bool IsShark;
}
protected override FishProperties makeNew( Int32 Id )
{
return new FishProperties()
{
IsShark = true
};
}
}
[RoutePrefix( "api/v3/Dog" )]
public class DogController : AnimalController<DogController.DogProperties>
{
public class DogProperties
{
public string Breed;
public Int32 TagNo;
}
protected override DogProperties makeNew( Int32 Id )
{
return new DogProperties()
{
Breed = "Labrador",
TagNo = 12345
};
}
}
}
当我运行这个API调用时:
localhost/api/v3/Dog/1
使用标题
Accept: text/xml
我遇到了这个错误:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace />
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>Type 'Areas.API.AnimalReturn`1[[Areas.API.DogController+DogProperties, NbtWebApp, Version=2012.2.4.1, Culture=neutral, PublicKeyToken=null]]' with data contract name 'AnimalReturnOfDogController.DogPropertiesS2PP9ThI:http://schemas.datacontract.org/2004/07/Areas.API' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.</ExceptionMessage>
<ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType>
<StackTrace> at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()</StackTrace>
</InnerException>
</Error>
然而,当我移除继承关系(注意AnimalReturn2),问题就消失了:
using System;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web.Http;
namespace Areas.API
{
public abstract class AnimalController<TProperties> : ApiController
where TProperties : new()
{
protected abstract TProperties makeNew( Int32 Id );
[Route( "{id}" )]
public AnimalReturn2<TProperties> Get( Int32 id )
{
TProperties p = makeNew( id );
return new AnimalReturn2<TProperties>()
{
Properties = p,
Request = Request,
StatusCode = HttpStatusCode.OK
};
}
}
public class AnimalReturn2<TProperties> : IHttpActionResult
{
public TProperties Properties;
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
public Task<HttpResponseMessage> ExecuteAsync( System.Threading.CancellationToken cancellationToken )
{
HttpResponseMessage response = null;
if( null != Request )
{
response = Request.CreateResponse( StatusCode, this );
}
return Task.FromResult( response );
} // ExecuteAsync()
}
[RoutePrefix( "api/v3/Fish" )]
public class FishController : AnimalController<FishController.FishProperties>
{
public class FishProperties
{
public bool IsShark;
}
protected override FishProperties makeNew( Int32 Id )
{
return new FishProperties()
{
IsShark = true
};
}
}
[RoutePrefix( "api/v3/Dog" )]
public class DogController : AnimalController<DogController.DogProperties>
{
public class DogProperties
{
public string Breed;
public Int32 TagNo;
}
protected override DogProperties makeNew( Int32 Id )
{
return new DogProperties()
{
Breed = "Labrador",
TagNo = 12345
};
}
}
}
现在当我发送同样的请求时,我得到的结果是:
<AnimalReturn2OfDogController.DogPropertiesS2PP9ThI
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/Areas.API">
<Properties>
<Breed>Labrador</Breed>
<TagNo>12345</TagNo>
</Properties>
</AnimalReturn2OfDogController.DogPropertiesS2PP9ThI>
问题是:是否有一种方法可以解决XML序列化问题,同时仍然使用继承?
我尝试过在不同的地方和不同的组合中使用KnownTypes(如此处建议:Unexpected Type - Serialization Exception 和这里:"Type not expected", using DataContractSerializer - but it's just a simple class, no funny stuff?),虽然我仍然怀疑那里有一个简单的答案。
我也试图禁用代理类,但似乎没有帮助。
谢谢。