3

我的任务是使用 C# WCF RESTful(即 Web)服务以 CSV 格式发送数据。目前,我有代码设置以 JSON 格式发送数据。

如何以 CSV 格式发送数据?

注意:这实际上不是我正在使用的文件集。这只是一个示例,展示了我如何构建我的服务并帮助修改它以用于 CSV 输出。

IService1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService4
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(
            Method = "GET", 
            UriTemplate = "employees",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        List<Employee> GetEmployees();
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Employee
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public int Age { get; set; }

        public Employee(string firstName, string lastName, int age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }
    }
}

服务1.svc.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Net;

namespace WcfService4
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public List<Employee> GetEmployees()
        {
            // In reality, I'm calling the data from an external datasource, returning data to the client that exceeds 10 MB and can reach an upper limit of at least 30 MB.               

            List<Employee> employee = new List<Employee>();
            employee.Add(new Employee("John", "Smith", 28));
            employee.Add(new Employee("Jane", "Fonda", 42));
            employee.Add(new Employee("Brett", "Hume", 56));

            return employee;
        }
    }
}
4

1 回答 1

5

有两种方法可以做到这一点。首先是编写一个新的实现IDispatchMessageFormatter,它知道如何理解 CSV 文件并将其“反序列化”为适当的类型。您可以在http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx找到有关它的更多信息。

另一种更简单的方法是使用“原始编程模型”,其中您的操作返回类型声明为Stream,并且您的操作可以返回 CSV 格式的数据。您可以在http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx找到有关该模式的更多信息。

于 2013-06-19T18:02:29.047 回答