0% found this document useful (0 votes)
18 views12 pages

Unit-4 Creating ASPdotnet Core MVC Application3

Uploaded by

lastminprep2022
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
18 views12 pages

Unit-4 Creating ASPdotnet Core MVC Application3

Uploaded by

lastminprep2022
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 12

Web API Applications

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:

BadRequest: Returns 400 status code.


Ok: Returns a 200 status code along with the result object.
NotFound: Returns 404 status code.
PhysicalFile: Returns a file.
Typically you want to return data and HTTP status codes from an API controller, To
that end there are three ways to return values from an API controller.

Return specific type


This is the most simplistic and straightforward way to return values from an API.
Consider the following API action:
[HttpGet]
public List<Customer> Get()
{
return db.Customers.ToList();
}
In this approach the Get() action returns a known type - List of Customer objects in
this case. This approach is good if you simply want to return data to the client
without accounting for unexpected conditions such as exceptions and HTTP codes
such as 404 and 200.
Return IActionResult
When your return value is a mix of data and HTTP codes you can't use the previous
approach. That's because the return type is a fix well-known type. If you want to
return NotFoundResult or OkResult or ObjectResult you can't use the preceding
approach. In such case you can return the values as IActionResult. Consider the
following example:

[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 (JavaScript Object Notation) is a lightweight data-interchange format. It is


easy for humans to read and write. It is easy for machines to parse and generate.
The new built-in JSON support, System.Text.Json, is high-performance, low
allocation, and based on Span<byte>. This is all automatic and built in with
.NET Core 3.0. But if your project is targeting to .NET Standard or .NET
framework (v4.6.1+), then you need to install the System.Text.Json NuGet
package, or you can continue to use Json.NET or other popular JSON libraries.

The System.Text.Json namespace provides high-performance, low-allocating, and standards-compliant


capabilities to process JavaScript Object Notation (JSON), which includes serializing objects to JSON
text and deserializing JSON text to objects, with UTF-8 support built-in. It also provides types to
read and write JSON text encoded as UTF-8, and to create an in-memory document object model
(DOM) for random access of the JSON elements within a structured view of the data.
Serializing object as JSON string using Serialize() Method

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)
{

string stringData = JsonSerializer.Serialize(stud);

var contentData = new StringContent(stringData, System.Text.Encoding.UTF8,


"application/json");

HttpResponseMessage response = client.PutAsync("http://localhost/api/student/",


contentData).Result;
string msg = JsonSerializer.Deserialize<string>(response.Content.ReadAsStringAsync().Result);
}

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;

public void GetStudent()


{
HttpResponseMessage response = client.GetAsync("http://localhost/api/students").Result;
string stringData = response.Content.ReadAsStringAsync().Result;
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
Student obj = JsonSerializer.Deserialize<Student>(stringData, options);
}
The GetStudent() method invokes the Customers Web API by making a GET
request using GetAsync() method. The Student data is returned from
the Web API and is read using the ReadAsStringAsync() method. The
string returned by ReadAsStringAsync() method contains JSON serialized
student data. This string data needs to be deserialized into a Student
object so that it can be used further in the client application.

To deserialize the JSON data the code uses Deserialize<T>() method of


JsonSerializer class from System.Text.Json.Serialization namespace. The
Deserialize<T>() method takes the string JSON data and settings to be
used while deserializing the data. The settings are supplied through
JsonSerializerOptions class. When a Student object is returned by the
Web API, the serialized property names use camel casing. While
deserializing the data you need to tell the JsonSerializer class that
deserialization should ignore the character casing. So,
PropertyNameCaseInsensitive property of JsonSerializerOptions is set to
true.If the Deserialize() method is successful the obj will contain a
Student object to use further.

You might also like