logo

,

Content Negotiation In Asp.net Core Web API

This article will discuss Content Negotiation in asp.net core web API.

What is Content Negotiation?

It is a mechanism where the client should be able to decide the format of the response from the server. For example, if the client wants the response in either XML, JSON, HTML, etc.
When a client sends a request to the server, the request includes Accept header which is used to determine the appropriate response format for the client.

 

Implementing Content Negotiation in Asp.net Core Web API project:

Step 1  – Create Ap.net Core Web API project.

Step 2 – Add a new Web API controller by the name StudentsController

Step 3 – We will add a class by name Student in the StudentsController.cs file and create a Controller Action method that will return us the list of students. Your StudentsController.cs file should be as below


    [Route("api/[controller]")]
    [ApiController]
    public class StudentsController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<Student> Get()
        {
            List<Student> students = new List<Student>();

            for (int i = 1; i <= 5; i++)
            {
                Student obj = new Student
                {
                    Id = i,
                    Name = "Student " + i
                };

                students.Add(obj);
            }

            return students;
        }
    }

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Step 4 – Go to the Startup.cs file and add the below code in your ConfigureServices method.

Note: If you are using .Net 6 and above, the below code should be added to the Program.cs file, as the Startup.cs file is not available from .Net 6 and onwards.

What Happened to Startup.cs File in .Net 6?
services.AddMvc().AddXmlSerializerFormatters();

By adding this line of code the API will return the response according to our choice.

Step 5 – Run the application, go to the postman application, and enter the GET request URL.

Step 6 – Add the Accept Header value as application/json

As we have entered the Accept header as application/json we should expect the response in json format.

Click Send button.

Now change the Accept header value to application/xml.

As expected, we have received the response in XML format.

3 Responses

Leave a Reply

Your email address will not be published.

Share on facebook
Share on twitter
Share on linkedin

Related articles