use*_*236 3 c# csv rest wcf web-services
我的任务是使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有两种选择可以做到这一点。首先是编写的新实现,该实现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上找到有关该模式的更多信息。
| 归档时间: |
|
| 查看次数: |
7286 次 |
| 最近记录: |