如何从 WEB API 请求和响应 XML 中删除命名空间?

How to remove namespace from WEB API request & response XML?

我想从 WEB API 请求和响应中删除突出显示的节点。 以下是网络中使用的 class 模型 api

 [DataContract(Namespace = "")]
    public class ValidateRequest
    {
        [DataMember]
        public string Client_Code { get; set; }
        [DataMember]
        public string ClientValidateNo { get; set; }
        [DataMember]
        public string UserID { get; set; }
        [DataMember]
        public string Password { get; set; }
    }

[DataContract(Namespace = "")]
    public class ValidateResponse
    {
    }

I want to remove highlighted node from WEB API request and response. Below are the class Models used in web api

要实现这个功能,首先需要创建一个继承自XmlSerializerOutputFormatter的class:

public class XmlSerializerOutputFormatterNamespace : XmlSerializerOutputFormatter
        {
            protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
            {
                //applying "empty" namespace will produce no namespaces
                var emptyNamespaces = new XmlSerializerNamespaces();
                emptyNamespaces.Add("", "any-non-empty-string");
                xmlSerializer.Serialize(xmlWriter, value, emptyNamespaces);
            }
        }

然后,在startup.cs中的ConfigureServices中添加如下服务:

 services
    .AddMvc(options =>
    {
        options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
    }).AddXmlSerializerFormatters();

在api方法中:

   [Produces("application/xml")]
    public IActionResult GetXml(ValidateRequest request)
    {
        ValidateResponse response = new ValidateResponse()
        {
            Amount = 100,
            ClientValidateNo = request.ClientValidateNo,
            Client_Code = request.Client_Code,
            DepositorCity = "aaa",
            DepositorName = "das",
            DepositorState = "sadasd",
            Status = "fasfas"
        };
        return Ok(response);
    }

测试结果: