c# - 在 asp.net core 2.1 中生成不适用于 xml 的数据注释
问题描述
我正在使用[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格式。
Product
一般情况下,我们会像使用 xml 格式化程序一样返回 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();
推荐阅读
- asp.net - 网格视图内的网格视图 网格视图内的网格视图
- bootstrap-4 - Bootstrap 侧视图在小屏幕中移至底部
- c# - 关于在 C# 中获取后台进程
- python - 检查一个基本的python函数
- google-analytics - 谷歌分析实时+历史数据
- acumatica - 将自定义字段添加到账单和调整屏幕会导致“可为空的对象必须具有值”
- python - StereoBM 在静态图像和视频输出上的不同结果
- symfony - 在 Symfony 5 的模板子文件夹中使用公用文件夹中的文件
- macos - 运行简单的 Selenium Runner 测试时出现“NoSuchSessionError:此驱动程序实例没有有效的会话 ID”
- flask - Falsk "ssl_context" 指向 Google 颁发的 SSL 证书