In this article I will explain with an example, how to display Formatted XML in Browser in ASP.Net Core MVC.
The XML file will be read as string and then its contents will be written to the Response as XML which will ultimately display the Formatted XML in Browser in ASP.Net Core MVC.
XML File Location
The XML file is present inside the wwwroot Folder (Directory).
XML File URL
The following XML file will be used in this article.
<?xml version="1.0" standalone="yes"?>
<Customers>
<Customer>
<Id>1</Id>
<Name>John Hammond</Name>
<Country>United States</Country>
</Customer>
<Customer>
<Id>2</Id>
<Name>Mudassar Khan</Name>
<Country>India</Country>
</Customer>
<Customer>
<Id>3</Id>
<Name>Suzanne Mathews</Name>
<Country>France</Country>
</Customer>
<Customer>
<Id>4</Id>
<Name>Robert Schidner</Name>
<Country>Russia</Country>
</Customer>
</Customers>
Namespaces
You will need to import the following namespaces.
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside the Index Action method, first the Response properties are set using IHttpContextAccessor interface.
ContentType – It informs the Browser about the file type. In this case it is XML.
Once the Response properties are set, the path of the XML file is fetched from the wwwroot path using IHostingEnvironment interface.
The XML file contents are read as string using ReadAllText method of File class and then stored in a string variable.
Finally, the string variable i.e. XML file contents are sent to the Client Browser as string using the Content method.
public class HomeController : Controller
{
private IHostingEnvironment Environment { get; set; }
private IHttpContextAccessor Accessor;
public HomeController(IHostingEnvironment _environment, IHttpContextAccessor _accessor)
{
this.Environment = _environment;
this.Accessor = _accessor;
}
public IActionResult Index()
{
//Set the Response properties.
this.Accessor.HttpContext.Response.Clear();
this.Accessor.HttpContext.Response.Headers.Add("Charset", "");
this.Accessor.HttpContext.Response.Headers.Add("Content-Type", "application/xml");
//Read the XML file contents as String.
string path = Path.Combine(this.Environment.WebRootPath, "Customers.xml");
string xml = System.IO.File.ReadAllText(path);
return Content(xml);
}
}
View
There is no HTML required inside the View and hence this section is skipped except.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads