In this article, we will focus on how XML is returned from the SP.NET Core Web API.ASP.NET Core is a powerful and effective development platform for building web applications.
The ASP.NET Web API provides developers with a powerful and flexible way to create and manage web services, it supports various data formats such as JSON, XML, and others.
To understand the process of how XML is returned from the SP.NET Core Web API, we first need to create a Web API that takes an XML data entry. Next, we will send this data to the client via SP.NET Core Web API. Finally, on the client side, we will parse and use this XML data.
In this example, we will use XML serialization to serialize data from XML using SP.NET Core Web API, and then send this XML data to the client. One thing to note here is that ASP.NET Core Web API supports XML and JSON data formats by default, but here we are focusing on a xml example.
To understand how to return XML from an ASP.NET Core Web API, let's use a Professor model as an example with fields such as Id, Name, Course, and Department.
public class Professor
{
public int Id { get; set; }
public string Name { get; set; }
public string Course { get; set; }
public string Department { get; set; }
}
Configure XML Formatter: Now we are going to configure the XML output formatter in the Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddXmlSerializerFormatters(); // Add XML support
}
If you are using .NET 7 or .NET 8, there is no Startup.cs class. In this case, we need to configure the XML formatter method in `Program.cs`.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddXmlDataContractSerializerFormatters();
Create Web API Controller: Here we have created a controller that returns the Professor model in XML format
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class ProfessorsController : ControllerBase
{
// GET: api/Professors
[HttpGet]
[Produces("application/xml")] // Specify XML output
public IActionResult GetProfessors()
{
var professors = new List<Professor>
{
new Professor { Id = 1, Name = "John Doe", Course = "Computer Science", Department = "Engineering" },
new Professor { Id = 2, Name = "Jane Smith", Course = "Mathematics", Department = "Science" }
};
return Ok(professors); // Return professors in XML format
}
}
Read Similar Articles
- [Solved] Error : java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
- [Solved]-"error processing condition on org.springframework.boot.autoconfigure.context.propertyplaceholderautoconfiguration.propertysourcesplaceholderconfigurer"
- [2024]- How to pass a login and password via POST using VBA HttpRequest
- How to consume third party REST API from ASP.NET Core?
- Download Free Sample Json File With Multiple Records