我正在为采用XML主体的API创建HttpPost端点,对接收到的数据进行一些处理,向外部API发送请求,然后以XML格式从外部API返回数据。
在此过程中,我与多个不同的类进行序列化和反序列化。我遇到的问题是这些序列化器的构造函数需要花费相对较长的时间加载,并且会影响我的API的响应时间。
这是当前的序列化/反序列化代码:
public static T DeserializeObject<T>(Stream objectStream)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StreamReader stream = new StreamReader(objectStream))
{
return (T)serializer.Deserialize(stream);
}
}
catch (Exception ex)
{
HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
message.Content = new StringContent("Error deserializing type: " + typeof(T).ToString() + Environment.NewLine
+ ex.Message
+ (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : string.Empty));
throw new HttpResponseException(message);
}
}
public static string SerializeObject<T>(T objectToSerialize)
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream,Encoding.UTF8))
{
xmlSerializer.Serialize(writer,objectToSerialize);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
catch (Exception ex)
{
HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
message.Content = new StringContent("Error serializing type: " + typeof(T).ToString() + Environment.NewLine
+ ex.Message
+ (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : string.Empty));
throw new HttpResponseException(message);
}
}
我有一些相当复杂的类正在被序列化,但是由于不得不向外部API发送请求,这是不可避免的。由于第三方与API集成,我也被限制使用XML
如何提高XML序列化器的性能并加快API的响应时间?