簡體   English   中英

生成數據注釋不適用於 asp.net core 2.1 中的 xml

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM