Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在WCF REST中创建XML响应_Xml_Wcf_Rest - Fatal编程技术网

如何在WCF REST中创建XML响应

如何在WCF REST中创建XML响应,xml,wcf,rest,Xml,Wcf,Rest,我想生成以下XML: <data contentType="text/plain" contentLength="24"> <![CDATA[OK - 12/05/2016 14:45:40]]> </data> 我的程序运行得很好,但我觉得必须有另一种方法来生成这种XML [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml,

我想生成以下XML:

<data contentType="text/plain" contentLength="24">
    <![CDATA[OK - 12/05/2016 14:45:40]]>
</data>

我的程序运行得很好,但我觉得必须有另一种方法来生成这种XML

[WebInvoke(Method = "GET", 
           ResponseFormat = WebMessageFormat.Xml, 
           BodyStyle = WebMessageBodyStyle.Bare, 
           RequestFormat = WebMessageFormat.Xml, 
           UriTemplate = "ping")]
Stream PingServer();

public Stream PingServer()
{
    string LeUrl = "http://yyyyy.fr/Service1.svc";
    string Result = "";

    try
    {
        var myRequest = (HttpWebRequest)WebRequest.Create(LeUrl);

        var response = (HttpWebResponse)myRequest.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            //  it's at least in some way responsive
            //  but may be internally broken
            //  as you could find out if you called one of the methods for real
            //Debug.Write(string.Format("{0} Available", url));

            Result = "OKE --" + DateTime.Now ;
        }
        else
        {
            //  well, at least it returned...
            //Debug.Write(string.Format("{0} Returned, but with status: {1}", url, response.StatusDescription));
            Result = response.StatusDescription;
        }
   }
   catch (Exception ex)
   {
       //  not available at all, for some reason
       //Debug.Write(string.Format("{0} unavailable: {1}", url, ex.Message));
       Result = ex.Message;
   }

   WebOperationContext CurrentWebContext = WebOperationContext.Current;
   CurrentWebContext.OutgoingResponse.ContentType = "text/plain";   

   String AnyXml = "<data contentType=\"text/plain\" contentLength=\"24\">"+"><![CDATA[OK - "+DateTime.Now+"]]></data>";

   return new MemoryStream(Encoding.UTF8.GetBytes(AnyXml)); 
}
[WebInvoke(Method=“GET”,
ResponseFormat=WebMessageFormat.Xml,
BodyStyle=WebMessageBodyStyle.Bare,
RequestFormat=WebMessageFormat.Xml,
UriTemplate=“ping”)]
流PingServer();
公共流服务器()
{
字符串LeUrl=”http://yyyyy.fr/Service1.svc";
字符串结果=”;
尝试
{
var myRequest=(HttpWebRequest)WebRequest.Create(LeUrl);
var response=(HttpWebResponse)myRequest.GetResponse();
if(response.StatusCode==HttpStatusCode.OK)
{
//它至少在某种程度上是有反应的
//但可能是内部破裂
//如果你真的调用了其中一个方法
//Debug.Write(string.Format(“{0}可用”,url));
Result=“OKE--”+DateTime.Now;
}
其他的
{
//好吧,至少它回来了。。。
//Write(string.Format(“{0}返回,但状态为:{1}”,url,response.StatusDescription));
结果=响应。状态描述;
}
}
捕获(例外情况除外)
{
//由于某种原因,根本不可用
//Debug.Write(string.Format(“{0}不可用:{1}”,url,ex.Message));
结果=例如消息;
}
WebOperationContext CurrentWebContext=WebOperationContext.Current;
CurrentWebContext.OutgoingResponse.ContentType=“text/plain”;
字符串AnyXml=”“+“>”;
返回新的MemoryStream(Encoding.UTF8.GetBytes(AnyXml));
}
我认为应该使用
xmlement
或类似的东西


我不想自己创建XML语法。

您可以使用XmlSerializer实现这一点-使用适当的System.XML.Serialization属性(即XmlRoot、XmlAttribute等)定义数据类型,并使用
[XmlSerializerFormat]
声明您的操作

下面的代码显示了您的场景可能的实现。请注意,它强制使用CData(这是您在问题中遇到的),但是如果您不需要它,则不需要在类中具有额外的属性

public class StackOverflow_37187563
{
    [XmlRoot(ElementName = "data", Namespace = "")]
    public class Data
    {
        [XmlAttribute(AttributeName = "contentType")]
        public string ContentType { get; set; }
        [XmlAttribute(AttributeName = "contentLength")]
        public int ContentLength { get; set; }
        [XmlElement]
        public XmlCDataSection MyCData
        {
            get { return new XmlDocument().CreateCDataSection(this.Value); }
            set { this.Value = value.Value; }
        }
        [XmlIgnore]
        public string Value { get; set; }
    }

    [ServiceContract]
    public class MyService
    {
        [WebGet(ResponseFormat = WebMessageFormat.Xml), XmlSerializerFormat]
        public Data PingServer()
        {
            return new Data
            {
                ContentLength = 24,
                ContentType = "text/plain",
                Value = "OK - 12/05/2016 14:45:40"
            };
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(MyService), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/PingServer"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

您可以为此使用XmlSerializer—使用适当的System.Xml.Serialization属性(即XmlRoot、XmlAttribute等)定义数据类型,并使用
[XmlSerializerFormat]
声明您的操作

下面的代码显示了您的场景可能的实现。请注意,它强制使用CData(这是您在问题中遇到的),但是如果您不需要它,则不需要在类中具有额外的属性

public class StackOverflow_37187563
{
    [XmlRoot(ElementName = "data", Namespace = "")]
    public class Data
    {
        [XmlAttribute(AttributeName = "contentType")]
        public string ContentType { get; set; }
        [XmlAttribute(AttributeName = "contentLength")]
        public int ContentLength { get; set; }
        [XmlElement]
        public XmlCDataSection MyCData
        {
            get { return new XmlDocument().CreateCDataSection(this.Value); }
            set { this.Value = value.Value; }
        }
        [XmlIgnore]
        public string Value { get; set; }
    }

    [ServiceContract]
    public class MyService
    {
        [WebGet(ResponseFormat = WebMessageFormat.Xml), XmlSerializerFormat]
        public Data PingServer()
        {
            return new Data
            {
                ContentLength = 24,
                ContentType = "text/plain",
                Value = "OK - 12/05/2016 14:45:40"
            };
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        WebServiceHost host = new WebServiceHost(typeof(MyService), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        Console.WriteLine(c.DownloadString(baseAddress + "/PingServer"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}