This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

ASP.NET Web API-Data Formats


In a Web API, data is typically exchanged in a structured format that is easy to parse and understand by both the server and client applications. The most commonly used data formats in Web APIs are JSON (JavaScript Object Notation) and XML (eXtensible Markup Language).

ASP.NET web API Data Formats

Let's explore each format.

JSON (JavaScript Object Notation)

JSON is a lightweight, text-based data interchange format. It is easy for humans to read and write and easy for machines to parse and generate. Data in JSON is represented as key-value pairs, similar to object literals in JavaScript. `JSON has become the de facto standard for data exchange in most modern Web APIs.

JSON is based on two types of structures.

  • A group of name/value combinations. This is implemented as an object, record, struct, dictionary, hash table, keyed list, or associative array in a variety of languages.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Example JSON data

[
    {
        "Id": 1,
        "Name": "TutorialsTrend",
        "Url": "https://tutorialstrend.com/"
    },
    {
        "Id": 2,
        "Name": "StackOverflow",
        "Url": "http://stackoverflow.com/"
    }
]

XML (eXtensible Markup Language)

XML is a markup language that defines rules for encoding documents in a format that is both human-readable and machine-readable. It uses tags to define elements and attributes to provide additional information about those elements. XML is more verbose compared to JSON and is often used in legacy systems or when specific requirements call for it.

Example XML data

<Blog>
<Id>1</Id>
<Name>TutorialsTrend</Name>
<Url>https://tutorialstrend.com/</Url>
</Blog>
<Blog>
<Id>2</Id>
<Name>StackOverflow</Name>
<Url>http://stackoverflow.com/</Url>
</BlogController.Blog>
</Blog>

Adding Controller in Application

After adding Web API project, you need to add one controller. Just right click on Controllers folder and Add Controller as named BlogController and add the following below code.

ASP.NET web API Data Formats

Within your controller, define the methods that will handle incoming HTTP requests and return responses.

For example, a simple GET method might look like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace webapiExample.Controllers
{
    public class BlogController : ApiController
    {
        public class Blog
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Url { get; set; }
        }
        public static List blogList = new List()
        {
            new Blog { Id = 1, Name="TutorialsTrend", Url="https://tutorialstrend.com/"},
            new Blog { Id = 2, Name="StackOverflow", Url="http://stackoverflow.com/"},
        };

        // GET api/Blog  
        public List Get()
        {
            return blogList;
        }
    }
}

Send results in different forms, such as XML and JSON

After creating the WebAPI, we must host the client service. There are several client kinds with various need types. Meaning that some clients want the output in XML format, while other clients require it in JSON format. Web API typically gives results in XML format. In order to support both formats, our service must thus add code to the WebApiConfig.cs file.

We shall compel the user to submit us the information in the format they specify in order to fulfill the aforementioned criterion. Additionally, they will convey the information by using extra parameters like the url shown below:

https://localhost:44376/api/blog?type=json
https://localhost:44376/api/blog?type=xml

If client need data in JSON format then type=json and same way if it is XML then type=xml,

Here is the complete code you need to add in WebApiConfig.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;

namespace webapiExample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            // Adding formatter for Json   
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));

            // Adding formatter for XML   
            config.Formatters.XmlFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
        }
    }
}

Now run the application and test it with return type as JSOn and XML.

Here, client number one requires information in XML, so go to the URL:

https://localhost:44376/api/blog?type=xml.

To show the result, refer to the following figure.

ASP.NET web API Data Formats

Here, client number one requires information in JSON, so go to the URL

https://localhost:44376/api/blog?type=json.

To show the result, refer to the following figure.

ASP.NET web API Data Formats
Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#