【发布时间】:2019-08-01 11:34:16
【问题描述】:
我正在使用[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。我无法理解问题。
【问题讨论】:
-
你有没有看过here也许它可以提供一些帮助
-
@lzzy 是的,我也关注了这个。但还是不行。
-
您要发送哪个接受标头? aspnet 将返回请求的格式,因此您需要请求 XML 获取 XML
-
客户端必须明确请求内容格式。见Content Negotiation
-
使用
XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9") + "urlset"添加命名空间。
标签: c# xml asp.net-core