如何根据参数从RESTful WCF调用返回CSV或JSON?

时间:2015-12-28 20:00:16

标签: c# json wcf rest csv

想象一下,我需要返回一个用户列表,结果必须是CSV或JSON格式。

/ users?format = json返回JSON / users?format = csv返回CSV

我尝试通过返回object的方法实现它:

// interface
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "users?format={format}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[ServiceKnownType(typeof(List<UserInfo>))]
[ServiceKnownType(typeof(Stream))]
object GetUsers(string format);

实现返回Stream或用户列表:

    public object GetUsers(string format)
    {
        if (format == null) format = "json";
        switch (format.ToLower())
        {
            case "json":
                return GetUsersJson(); // returns List<UserInfo>

            case "csv":
                return GetUsersCsv(); // returns MemoryStream

            default:
                return BadRequest("Invalid content format: " + format);
        }
    }

当我运行它时,JSON版本可以工作,但CSV版本因序列化异常而失败:

  

System.Runtime.Serialization.SerializationException:Type   &#39; System.IO.MemoryStream&#39;与数据合同名称   &#39; MemoryStream的:http://schemas.datacontract.org/2004/07/System.IO&#39;是   没想到。

如果我将ServiceKnownType(typeof(Stream))替换为ServiceKnownType(typeof(MemoryStream)),则没有例外,但下载的文件包含MemoryStream的JSON表示:

  

{&#34; __同一性&#34;:空,&#34; _buffer&#34;:[78,97,109,...,0,0,0,0],&#34; _capacity&#34; :256,   &#34; _expandable&#34;:真,&#34; _exposable&#34;:真,&#34; _isOpen&#34;:真,&#34; _length&#34;:74,   &#34; _origin&#34;:0,&#34; _position&#34;:74,&#34; _writable&#34;:真}

这不是我在返回流时的想法:)

那么,有没有办法以多态方式返回Stream,还是必须使用两个不同的调用?

1 个答案:

答案 0 :(得分:1)

您的响应格式设置为WebMessageFormat.Json,这就是WCF返回JSON的原因。实现所需目标的一种方法是使用WCF "Raw" programming model,这意味着将方法的返回类型更改为Stream。完成此操作后,您告诉WCF您要控制响应,并且它不会对数据应用任何格式。然后,您可以使用内置的DataContractJsonSerializer(或任何其他序列化程序)将JSON字符串序列化到流中。在任何一种情况下,请务必将WebOperationContext.Current.OutgoingResponse.ContentType设置为适当的值。