首页 > 解决方案 > 在 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。我无法理解问题。

标签: c#xmlasp.net-core

解决方案


对于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();

推荐阅读