如何使用c# WCF RESTful(即Web)服务发送CSV文件
本文关键字:服务 文件 CSV Web 何使用 WCF RESTful | 更新日期: 2023-09-27 18:19:01
我的任务是使用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;
}
}
}
有两种选择。第一个是编写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找到有关该模式的更多信息。