当我将使用泛型类型的返回对象序列化为
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?),但我仍然怀疑在那里有一个简单的答案.
我也试过禁用代理类,但这似乎没有帮助.
谢谢.
最佳答案 序列化是在基类方法AnimalResult.ExecuteAsync()内完成的,它调用
HttpRequestMessageExtensions.CreateResponse<T> Method (HttpRequestMessage, HttpStatusCode, T)
:
response = Request.CreateResponse( StatusCode, this );
由于这是静态类型为AnimalResult,因此该类型成为传递给扩展方法的泛型参数T.因此,尝试将从它派生的类型作为KnownType属性添加到AnimalResult:
[KnownType(typeof(AnimalReturn<DogController.DogProperties>))]
[KnownType(typeof(AnimalReturn<FishController.FishProperties>))]
public class AnimalResult : IHttpActionResult
{
}
您还应该能够通过使用MakeGenericMethod()
调用HttpRequestMessageExtensions.CreateResponse< T>来使其工作.使用this.GetType()作为类型参数.见How to invoke static generic class methods if the generic type parameters are unknown until runtime?
更新
下面是一个如何使用返回的AnimalResult的实际类型在运行时调用静态泛型方法的示例,从而避免需要将AnimalResult的所有可能派生类定义为已知类型:
public class AnimalResult : IHttpActionResult
{
[IgnoreDataMember]
public HttpStatusCode StatusCode = HttpStatusCode.OK;
[IgnoreDataMember]
public HttpRequestMessage Request = null;
private static HttpResponseMessage StaticCreateResponse<TAnimalResult>(TAnimalResult animalResult) where TAnimalResult : AnimalResult
{
if (animalResult == null)
throw new ArgumentNullException(); // Should have been checked outside.
Debug.Assert(typeof(TAnimalResult) == animalResult.GetType());
return animalResult.Request.CreateResponse(animalResult.StatusCode, animalResult);
}
HttpResponseMessage CreateResponse()
{
if (Request == null)
return null;
else
{
var method = typeof(AnimalResult).GetMethod("StaticCreateResponse", BindingFlags.NonPublic | BindingFlags.Static);
var genericMethod = method.MakeGenericMethod(new[] { GetType() });
return (HttpResponseMessage)genericMethod.Invoke(null, new object[] { this });
}
}
public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken )
{
var response = CreateResponse();
return Task.FromResult( response );
} // ExecuteAsync()
}