I've got a controller which returns a custom made XML string because the application that consumes the Api needs a specific format without any attributes and without the <?xml ... />
tag on top of default XML strings. EDIT: the consumer also doesn't have a request header that asks for 'text/xml'.
My ConfigureServices in my Startup.cs looks like this:
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();
}
In my controller, I've tried some solutions I've found on internet (commented out), but none give me the XML content with the response header 'Content-Type: application/xml' in chrome devtools:
[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") };
}
What can I try to get it respond with application/xml?
EDIT1 (after Luca Ghersi's answer): 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);
Controller:
[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());