[英]Produces data annotation not working for xml in asp.net core 2.1
我正在使用[Produces("application/xml")]
数据注释以XML
返回我的响应,但不幸的是它没有返回任何内容。 当我删除[Produces]
数据注释时,它会以 JSON 格式返回数据。 我还添加了AddXmlSerializerFormatters()
格式化程序。
这是我的控制器操作
[HttpGet("Generate")]
[Produces("application/xml")]
public XDocument Get()
{
XDocument sitemap = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("urlset", XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9"),
from item in business
select CreateItemElement(item)
)
);
return Ok(sitemap.ToString());
}
这是我在启动类中的 ConfigureService 方法
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<ListingDbContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("App4Rental_Website_DB")));
services.AddTransient<IRentalRepository, RentalRepository>();
services.AddTransient<IScrapingRepository, ScrapingRepository>();
}
它的工作正常 JSON 结果但不适用于 XML。 我无法理解问题。
对于XDocument
,不应将其序列化为 xml 格式。
通常,我们使用 xml 格式化程序返回类似Product
Object。 您可以尝试返回Product
来测试[Produces("application/xml")]
。
如果你想返回XDocument
,你可以考虑直接返回字符串
public string Get()
{
XDocument srcTree = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2"),
new XElement("Child3", "data3"),
new XElement("Child2", "data4"),
new XElement("Info5", "info5"),
new XElement("Info6", "info6"),
new XElement("Info7", "info7"),
new XElement("Info8", "info8")
)
);
XDocument doc = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
from el in srcTree.Element("Root").Elements()
where ((string)el).StartsWith("data")
select el
)
);
return doc.ToString();
}
更新:
预期的结果是由错误的 XDocument 创建引起的。 尝试如下:
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument sitemap = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new XElement(ns + "urlset",
new XElement(ns + "url",
new XElement(ns + "loc", "http://app4rental.com/business/100/r.s.-enterprises"),
new XElement(ns + "lastmod", "2019-08-01"),
new XElement(ns + "changefreq", "weekly"),
new XElement(ns + "priority", "0.8")
)));
return sitemap.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.