How to remove xml namespace when return type is ge

2019-09-03 06:40发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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);

        }

}


标签: c# .net wcf rest