我有一个控制器,它返回一个定制的 XML 字符串,因为使用 Api 的应用程序需要一种特定格式,没有任何属性,并且<?xml ... />
默认 XML 字符串顶部没有标签。编辑:消费者也没有请求“text/xml”的请求标头。
我的 Startup.cs 中的 ConfigureServices 如下所示:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
var mvc = services.AddMvc();
mvc.AddMvcOptions(options =>
{
options.InputFormatters.Remove(new JsonInputFormatter());
options.OutputFormatters.Remove(new JsonOutputFormatter());
});
mvc.AddXmlDataContractSerializerFormatters();
}
在我的控制器中,我尝试了一些我在互联网上找到的解决方案(已注释掉),但没有一个在 chrome devtools 中给我带有响应标头“Content-Type:application/xml”的 XML 内容:
[HttpGet("{ssin}")]
[Produces("application/xml")]
public string Get(string ssin)
{
var xmlString = "";
using (var stream = new StringWriter())
{
var xml = new XmlSerializer(person.GetType());
xml.Serialize(stream, person);
xmlString = stream.ToString();
}
var doc = XDocument.Parse(xmlString);
doc.Root.RemoveAttributes();
doc.Descendants("PatientId").FirstOrDefault().Remove();
doc.Descendants("GeslachtId").FirstOrDefault().Remove();
doc.Descendants("GeboorteDatumUur").FirstOrDefault().Remove();
doc.Descendants("OverledenDatumUur").FirstOrDefault().Remove();
Response.ContentType = "application/xml";
Response.Headers["Content-Type"] = "application/xml";
/*var response = new HttpResponseMessage
{
Content = new StringContent(doc.ToString(), Encoding.UTF8, "application/xml"),
};*/
return doc.ToString(); //new HttpResponseMessage { Content = new StringContent(doc., Encoding.UTF8, "application/xml") };
}
EDIT1(在 Luca Ghersi 的回答之后): Startup.cs:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
var mvc = services.AddMvc(config => {
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new XmlSerializerInputFormatter());
config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
mvc.AddMvcOptions(options =>
{
options.InputFormatters.Remove(new JsonInputFormatter());
options.OutputFormatters.Remove(new JsonOutputFormatter());
});
//mvc.AddXmlDataContractSerializerFormatters();
}
/*
* Preconfigure if the application is in a subfolder/subapplication on IIS
* Temporary fix for issue: https://github.com/aspnet/IISIntegration/issues/14
*/
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Map("/rrapi", map => ConfigureApp(map, env, loggerFactory));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void ConfigureApp(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//app.UseIISPlatformHandler();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
控制器:
[HttpGet("{ssin}")]
[Produces("application/xml")]
public IActionResult Get(string ssin)
{
var patient = db.Patienten.FirstOrDefault(
p => p.Rijksregisternummer.Replace(".", "").Replace("-", "").Replace(" ", "") == ssin
);
var postcode = db.Postnummers.FirstOrDefault(p => p.PostnummerId == db.Gemeentes.FirstOrDefault(g =>
g.GemeenteId == db.Adressen.FirstOrDefault(a =>
a.ContactId == patient.PatientId && a.ContactType == "pat").GemeenteId
).GemeenteId
).Postcode;
var person = new person
{
dateOfBirth = patient.GeboorteDatumUur.Value.ToString(""),
district = postcode,
gender = (patient.GeslachtId == 101 ? "MALE" : "FEMALE"),
deceased = (patient.OverledenDatumUur == null ? "FALSE" : "TRUE"),
firstName = patient.Voornaam,
inss = patient.Rijksregisternummer.Replace(".", "").Replace("-", "").Replace(" ", ""),
lastName = patient.Naam
};
var xmlString = "";
using (var stream = new StringWriter())
{
var opts = new XmlWriterSettings { OmitXmlDeclaration = true };
using (var xw = XmlWriter.Create(stream, opts))
{
var xml = new XmlSerializer(person.GetType());
xml.Serialize(xw, person);
}
xmlString = stream.ToString();
}
var doc = XDocument.Parse(xmlString);
doc.Root.RemoveAttributes();
doc.Descendants("PatientId").FirstOrDefault().Remove();
doc.Descendants("GeslachtId").FirstOrDefault().Remove();
doc.Descendants("GeboorteDatumUur").FirstOrDefault().Remove();
doc.Descendants("OverledenDatumUur").FirstOrDefault().Remove();
return Ok(doc.ToString());