控制来自 REST 服务的响应格式 [英] Controlling the response format from a REST service

查看:32
本文介绍了控制来自 REST 服务的响应格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 C# 编写的 REST 服务,它可以读取参数并返回一些值,但 XML 中没有足够的级别.

I have a REST service written in C# that can read in parameters and returns some values, but the XML doesn't have enough levels in it.

在它返回的那一刻:

<topNode>
    <item1>1</item1>
    <item2>2</item2>
    <item3>3</item3>
</topNode>

但我真正需要的是:

<topNode>
    <secondNode>
        <item1>1</item1>
        <item2>2</item2>
        <item3>3</item3>
    </secondNode>
</topNode>

我认为我需要做的是修改响应数据合同,但我不确定如何修改.目前是这样写的:

I think that what I need to do is amend the response data contract, but I'm not sure how. At present it is written like so:

[DataContract(Namespace = "http://example.com/myNamespace")]
public class dataResponse
{        
    [DataMember]
    public string item1 { get; set; }

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

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

因为如果遇到错误,我还需要返回具有不同元素名称的 XML,所以我希望返回一个我可以自己格式化的 XML 文档.

As I also need to return XML with different element names if an error is encountered I'd ideally like to return an XML document that I can format myself.

任何帮助/指针将不胜感激

Any help/pointers would be appreciated

推荐答案

WCF 方法有 3 种特殊的返回类型,可让您更好地控制返回给客户端的内容:

There are 3 special return types from a WCF method that give you more control over what is returned to the client:

System.ServiceModel.Channels.Message
Stream
byte[]

Stream 和字节数组只是将 Stream 或数组中的数据返回给客户端.对于消息对象,您需要使用消息对象中的静态 CreateMessage 重载之一来创建它的实例以返回.使用这些返回类型之一,您必须创建自己返回的 XML,但我认为这就是您在此处寻找的内容.例如,您可以执行以下操作:

Stream and the byte array are simply going to return the data in the Stream or array to the client. For the message object you will need to use one of the static CreateMessage overloads in the Message object to create an instance of it to return. Using one of these return types, you will have to create the XML that is returned yourself, but I think that is what you are looking for here. For example you could do something like this:

[ServiceContract]
public interface: IMyContract
{
     [OperationContract]
     [WebInvoke(Method = "GET", UriTemplate = "getXml")]
     Stream ReturnAnyXml();   
}

public class MyService : IMyContract
{
    public Stream ReturnAnyXml()
    {
        WebOperationContext CurrentWebContext = WebOperationContext.Current;
        if (CurrentWebContext != null)
        {
            CurrentWebContext.OutgoingResponse.ContentType = "text/xml";    
            String AnyXml = "<tag></tag>";
            return new MemoryStream(Encoding.UTF8.GetBytes(AnyXml)); 
        }
    }      
}  

这篇关于控制来自 REST 服务的响应格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆