我的 WCF web 服务必须返回 xml 文件以供下载,对于该功能,我需要序列化一个类的对象列表。这里的类定义:
[DataContract]
public class ReportItemDriversPerAffiliate : IReportItemDriversPerAffiliate
{
[DataMember(Name = "affiliate_name")]
public string AffiliateName { get; set; }
[DataMember(Name = "affiliate_city")]
public string AffiliateCity { get; set; }
[DataMember(Name = "affiliate_state")]
public string AffiliateState { get; set; }
[DataMember(Name = "drivers_count")]
public int DriversCount { get; set; }
}
对于此功能,我使用以下代码:
var totalDriversPerAffiliate = _glManager.GetTotalDriversPerAffiliate<ReportItemDriversPerAffiliate>();
XmlSerializer ser = new XmlSerializer(totalDriversPerAffiliate.GetType());
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, totalDriversPerAffiliate);
ms.Position = 0;
StreamReader r = new StreamReader(ms);
string res = r.ReadToEnd();
var context = System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse;
context.Headers.Add("Content-Disposition", "attachment; filename=TotalDriversPerAffiliate.xml");
context.ContentType = "application/txt";
byte[] resultBytes = Encoding.UTF8.GetBytes(res);
return new MemoryStream(resultBytes);
但是,在响应文件中,我在 xml 中有字段值,这些字段具有类属性的值,而不是 WCF 显示名称属性的值(具有“AffiliateName”,想要“affiliate_name”),我如何手动序列化此类并在 xml 中具有像显示这样的字段类的名称属性?而且,我不想向此类添加额外的 xml 属性,也不想在 Web 服务中创建单独的方法,该方法将此数据作为 xml 响应返回。