Introduction
By default, ASP.NET Core Web API application supports Json data in requests and responses without any additional code. We can add simple code to support XML requests and responses in Web API. We will see all the simple steps in this post.
Create ASP.NET Core 3.1 Web API application in Visual Studio 2019
We can create a simple Web API application in Visual studio with ASP.NET Core 3.1 framework.
We must modify ConfigureServices method in Startup class with below code. This will add XML data support to both requests and responses in all web methods. Json data format is added by default, in ASP.NET Core Web API application.
We can create a sample Employee model class to test our application.
Employee.cs
- namespace WebAPIXMLJson
- {
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string City { get; set; }
- }
- }
We can create an EmployeesController API class.
EmployeesController.cs
- using Microsoft.AspNetCore.Mvc;
- using System.Collections.Generic;
-
-
-
- namespace WebAPIXMLJson.Controllers
- {
- [Route("api/[controller]")]
- public class EmployeesController : Controller
- {
- [HttpGet("get.{format}"), FormatFilter]
- public IEnumerable<Employee> Get()
- {
- List<Employee> employees = new List<Employee>
- {
- new Employee { Id = 1, Name = "Sarath Lal",City="Cochin" },
- new Employee { Id = 2, Name = "Anil Kumar",City="Bangalore"}
- };
- return employees;
- }
-
- [HttpPost("post.{format}"), FormatFilter]
- public Employee Post([FromBody]Employee employee)
- {
- if (ModelState.IsValid)
- {
- return employee;
- }
- else
- {
- return null;
- }
- }
- }
- }
Replace Employee Controller code with above code snippet.
We have decorated HttpGet and HttpPost with .{format} and also with “FormatFilter”.
You must pass the response type as XML or Json in every requests.
We can check the application in Postman tool.
We can easily get the data in XML format
We have added .xml at the end of request.
We can get the data in Json format in the same way.
If you send the request without any format like “http://localhost:52737/api/employees/get” you will get 404, not found error.
We can pass the Employee data as XML format in Post method also using Postman.
I have chosen the raw data format and XML type in Postman. Please note the request format is json. So, that we have received the data in json format though we have sent the data as XML format. We must carefully pass the employee data model namespace in XML namespace. Otherwise, data will not pass correctly to Web API method.
Conclusion
In this simple post, we have seen how to get data from Web API as XML and Json format in same web request. We have also seen how to pass data as XML and JSON in same Post request as well. There are various ways to achieve this result. I found that, this is one of the easiest ways. If you have got any other easiest way, please feel free to write as a comment.