开发者

How to remove xml namespace when return type is generic type in wcf restful service

Following is interface definition.

[OperationContract]
[WebGet(UriTemplate = "FacebookData/?accessToken={accessToken}")]
OperationResult<FacebookData> GetFacebookData(string accessToken);

The return type is OperationResult<FacebookData>, it is a generic type

Then i will get xml like following...

OperationResultOfFacebookDataNcCATIYq开发者_开发知识库 xmlns:i="http://www.w3.org/2001/XMLSchema-instance"

How can I remove namespace and rename xml element as "OperationResult"

By the way, I already set Namespace is empty

[DataContract(Namespace = "")]
public class OperationResult<T>

but I think generic type will generate class by every T.


You can do [DataContract(Name = "OperationResult")] but really the generics conceptually don't mix will with the idea of RESTful services.

I'd suggest creating a new class like class FacebookOperationResult : OperationResult<FacebookData> {} and then use that as your return type.


One way to make that happen is to implement IDispatchMessageInspector - this allows to inspect and modify any request/reply content anyway you want/need...


to remove the xmlns you need to create your own serializer to bypass the serialization that is done by WCF.

Interface:

 [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "ProcessMessage")]
        AResponse ProcessMessage(ARequest content);
    }

Service: //change the behavior to one that suits you

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
    public class Service : IService
    {
        public AResponse ProcessMessage(ARequest content)
        {
         //todo  
        }
    }

Here comes the most important:

[XmlRoot("My_Root", Namespace = "")]
ARequest : IXmlSerializable
{
    public string PropertyA { get; set; }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return (null);
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            if (!reader.IsEmptyElement)
            {
                reader.ReadStartElement();
                PropertyA = reader.ReadElementString("PropertyA");
                reader.ReadEndElement();
            }
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteElementString("PropertyA", PropertyA);

        }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜