如何手动序列化对象使用wcf显示名称属性?

时间:2012-10-23 08:18:11

标签: .net xml wcf

我的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响应返回。

1 个答案:

答案 0 :(得分:0)

XmlSerializer忽略DataMember属性。试试NetDataContractSerializer。