簡體   English   中英

退貨清單 <object> 以Csv格式作為響應WCF C#

[英]Return List<object> in Csv format as response WCF C#

我想從我的WCF方法將類對象的列表作為csv文件返回。 我嘗試使用此處提供的MediaTypeFormatter實現自定義格式器

但是我無法在WCF服務方法中實現這一點。 有沒有一種方法可以在WCF中實現呢? 我可以以某種方式在ResponseFormat中設置自定義格式器,它將起作用嗎? 我正在尋找直接將我的列表轉換為csv的解決方案。 我在服務接口中定義了以下簡單的服務方法:

    [OperationContract]
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetDNCList")]
    List<DNC> GetDNCList();

此列表應作為csv文件發送給用戶

自定義格式器(和MediaTypeFormatter )在ASP.NET Web API框架中使用,而不在WCF中使用。 在此框架中,您需要使用IDispatchMessageFormatter來控制響應的格式化方式。 http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx上的帖子提供了有關如何實現此功能的詳細信息,下面的代碼顯示了一種方法為WCF實現CSV格式器的說明。

public class StackOverflow_23979866
{
    public class DNC
    {
        public string Field1 { get; set; }
        public string Field2 { get; set; }
        public string Field3 { get; set; }
    }
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetDNCList")]
        List<DNC> GetDNCList();
    }
    public class Service : ITest
    {
        public List<DNC> GetDNCList()
        {
            return new List<DNC>
            {
                new DNC { Field1 = "Value 1-1", Field2 = "Value 2-1", Field3 = "Value 3-1" },
                new DNC { Field1 = "Value 1-2", Field2 = "Value 2-2", Field3 = "Value 3-2" },
                new DNC { Field1 = "Value 1-3", Field2 = "Value 2-3", Field3 = "Value 3-3" },
            };
        }
    }
    public class MyWebHttpBehavior : WebHttpBehavior
    {
        protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            if (operationDescription.Name == "GetDNCList")
            {
                return new MyListOfDNCReplyFormatter();
            }
            else
            {
                return base.GetReplyDispatchFormatter(operationDescription, endpoint);
            }
        }
    }
    public class MyListOfDNCReplyFormatter : IDispatchMessageFormatter
    {
        public void DeserializeRequest(Message message, object[] parameters)
        {
            throw new NotSupportedException("This is a reply-only formatter");
        }

        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            List<DNC> list = (List<DNC>)result;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("\"Field1\",\"Field2\",\"Field3\"");
            foreach (var dnc in list)
            {
                // may need to escape, leaving out for brevity
                sb.AppendLine(string.Format("\"{0}\",\"{1}\",\"{2}\"", dnc.Field1, dnc.Field2, dnc.Field3));
            }

            Message reply = Message.CreateMessage(messageVersion, null, new RawBodyWriter(sb.ToString()));
            reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpResponseMessageProperty httpResp = new HttpResponseMessageProperty();
            reply.Properties.Add(HttpResponseMessageProperty.Name, httpResp);
            httpResp.Headers[HttpResponseHeader.ContentType] = "text/csv";
            return reply;
        }

        class RawBodyWriter : BodyWriter
        {
            string contents;
            public RawBodyWriter(string contents)
                : base(true)
            {
                this.contents = contents;
            }

            protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
            {
                writer.WriteStartElement("Binary");
                byte[] bytes = Encoding.UTF8.GetBytes(this.contents);
                writer.WriteBase64(bytes, 0, bytes.Length);
                writer.WriteEndElement();
            }
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "");
        endpoint.Behaviors.Add(new MyWebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/GetDNCList"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM