Unit-4 Creating ASPdotnet Core MVC Application3
Unit-4 Creating ASPdotnet Core MVC Application3
The ASP.NET Web API is an extensible framework for building HTTP based
services that can be accessed in different applications on different platforms
such as web, windows, mobile etc. It works more or less the same way as
ASP.NET Core MVC web application except that it sends data as a response
instead of html view. Web API handles JSON and XML data by default.
ASP.NET Core combines the best features of ASP.NET MVC and web APIs into a single framework.
This makes complete sense since they provide many similar functionalities. Both used to support
Controller and action methods. In earlier version, the main purpose of Web API was to make REST
API calls and there were view engine like Razor and MVC was designed for HTML front ends to
communicate to backend in a standard web application.
Before this merger, developers had to rewrite code when they needed to expose data in different
formats via MVC and web APIs. They had to work with multiple frameworks and concepts at the
same time. Fortunately, this entire process has been completely streamlined in ASP.NET Core and
main target is to support JSON based REST API. It combines the key feature of both MVC and old
Web API framework.
ASP.NET Web API is mainly based on the MVC architecture and share a number of APIs of
The .Net Framework and .Net Core.
API Controllers
ASP.NET Core supports creating RESTful services, also known as web APIs, using C#. To
handle requests, a web API uses controllers. Controllers in a web API are classes that
derive from ControllerBase.
API Controller is just a normal Controller, that allows data in the model to be retrieved
or modified, and then deliver it to the client. It does this without having to use the
actions provided by the regular controllers.
The data delivery is done by following a pattern known by name as REST. REST Stands
for REpresentational State Transfer pattern, which contains 2 things:
1. Action Methods which do specific operations and then deliver some data to the
client. These methods are decorated with attributes that makes them to be
invoked only by HTTP requests.
2. URLs which defines operational tasks. These operations can be – sending full or part
of a data, adding, deleting or updating records.
Creating Web APIs in ASP.NET Core is very straightforward. You create
a controllers that have 3 things:
1. They should have [ApiController] attribute on them. This attribute tells that the
controller will server HTTP API Responses.
2. They should derive from ControllerBase class instead of Controller class.
3. They should have attribute routing applied on them like
[Route("someUrl/[controller]")].
Eg:
[ApiController]
[Route("someURL/[controller]")]
public class ExampleController : ControllerBase
The reason why you must not create a Web API controller by deriving from the
Controller class is because the Controller class derives from ControllerBase class
and adds support for views, so it’s for handling web pages, not web API requests.
There’s an exception to this rule: if you plan to use the same controller for both
views and web APIs, then only derive it from Controller class.
The ControllerBase class provides many properties and methods that are useful for
handling HTTP requests. Some of these are:
[HttpGet("{id}")]
public IActionResult Get(string id)
{
Student stud = db.Students.Find(id);
if (stud == null)
{
return NotFound();
}
return Ok(stud);
}
Return ActionResult<T>
ActionResult<T> allows you to combine both of the approaches discussed earlier. You
can return a type derived from ActionResult or a specific type. Consider the following
Get() action:
[HttpGet("{id}")]
public ActionResult<Student> Get(string id)
{
Student stud = db.Students.Find(id);
if (stud == null)
{
return NotFound();
}
return stud;
}
As you can see you don't need to wrap cust object in Ok() or ObjectResult. You can
either return NotFoundResult or ActionResult<Student>
JSON Support
When two applications/servers/languages/etc need to communicate, they tend to do so
using strings, since strings can be interpreted in pretty much the same way in all languages.
While a complex data structure is often described internally in terms of memory references,
and represented with all kinds of curly, square, angle brackets or whitespace.. a string is just an
ordered series of characters.
JSON data can be sent from the client to the Web API. Consider the following code
that invokes the Put() action of the Web API.
public void UpdateStudent(Student stud)
{
To send this object to the Web API, first you need to serialize it into JSON format. This is done
using the Serialize() method of JsonSerializer class. The string data returned by the
Serialize() method is wrapped into a StringContent object and then passed to the
PutAsync() method.
Deserializing JSON data using Deserialize() method
suppose that you want to build a client application that uses .NET Core's HttpClient
class to invoke the
Get() and Put() actions. So, first step would be to use these namespaces:
using System.Text.Json;
using System.Text.Json.Serialization;