这个答案延迟了一年,并针对 WebAPI2 进行了测试!
WebApiConfig
在您的班级中启用 XML 声明
config.Formatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = false;
然后添加schemaLocation
属性或成员(我总是更喜欢属性)
public class SampleData
{
[XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string SchemaLocation { get; set; }
//other properties
public string Prop1 { get; set; }
public SampleData()
{
SchemaLocation = "http://localhost/my.xsd";
}
}
输出:
<?xml version="1.0" encoding="utf-8"?>
<TestModel
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://localhost/my.xsd">
<Prop1>1</Prop1>
</TestModel>