我的任务是使用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;
}
}
}
Service1.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;
}
}
}
答案 0 :(得分:4)
有两种方法可以做到这一点。第一个是编写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找到有关该模式的更多信息。