Overview of the MVC API in .NET 6

Tram Ho

1. MVC pattern

image.png

  • Model : is a place to store operations that interact with data or database management systems (mysql, mssql… ); it  will  include classes/functions that handle many operations such as database connection, data query, th• smooth –• delete •– edit•  data…
  • View : is a place to contain interfaces such as buttons, input frames, menus, images… it is responsible for displaying data and helping users interact with the system.
  • Controller : is the place to receive processing requests sent from users, it will include classes/functions that handle many logical operations to help get the right data and information needed by the services provided and displayed by the Model layer. that data out to the user thanks to the View class.
  • Interactions between components:
    • Controller interacts with View
    • Controller interacts with Model
    • Model and View do not interact with each other, but interact with each other through the Controller.

2. API

  • API stands for Application Programming Interface – application programming interface. It provides the ability to communicate between applications through the internet.

image.png

  • In the previous section without using the .net 6 api, the application will include a common backend and frontend. image.png
  • When using web api, it is common to separate the backend and the frontend separately. And the frontend website will communicate with the backend via the API, or there are mobile apps that will communicate with the backend via the API.
  • Web Apps

image.png

  • Mobile application

image.png

3. What is Restful?

  • RESTful API is a standard used in designing APIs for web applications (Web services design) to facilitate resource management. It focuses on system resources (text files, images, audio, video, or dynamic data, etc.), including resource states that are formatted and transmitted over HTTP. image.png
  • HTTP protocols:
    • GET (SELECT): Returns a Resource or a list of Resources.
    • POST (CREATE): Create a new Resource.
    • PUT (UPDATE): Update information for Resource.
    • DELETE (DELETE): Delete a Resource.
  • These methods or operations are often called CRUD corresponding to Create, Read, Update, Delete – Create, Read, Edit, Delete.

4. Status code

  • When we request an API, there are usually a few status codes to identify the following:
    • 200 OK – Returns success for GET, PUT, PATCH or DELETE methods.
    • 201 Created – Returns when a Resouce has been created successfully.
    • 204 No Content – ​​Returns when the Resource is successfully deleted.
    • 304 Not Modified – Client can use cached data.
    • 400 Bad Request – Invalid Request
    • 401 Unauthorized – Request requires auth.
    • 403 Forbidden – permission denied.
    • 404 Not Found – Resource not found from URI
    • 405 Method Not Allowed – The method is not allowed for the current user.
    • 410 Gone – Resource no longer exists, the old version is no longer supported.
    • 415 Unsupported Media Type – This Resource type is not supported.
    • 422 Unprocessable Entity – Data is not validated
    • 429 Too Many Requests – Request denied due to restriction
  • Read more about http code: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  • Corresponds to in .NET 6:
    • return Ok(Value) : return http code 200 and result.
    • return BadRequest(): return http code 400
    • return NotFound(): return http code 404
    • return NoContent(): return http code 204
    • return new UnsupportedMediaTypeResult(): return http code 415
  • Return HTML
    • The View() method will return a ViewResult which is an HTML response.
    • The PartialView() method will return a part of the View. Use when you want to update part of the view without reloading the entire view (useful in Single Page Application)
  • Return File
    • FileContentResult: reads a byte array and returns it as a file.
    • FileStreamResult: reads a stream and returns a file.
    • VirtualFileResult: reads file content from a relative path on hosting and returns it to the client.
    • PhysicalFileResult: reads file content from a physical path and returns it to the client.
  • Returns the text content
    • Content(value): ActionResult returns a specific content as plain text.
    • new JsonResult(value): This ActionResult returns data in JSON format. Is it possible to convert an object to JSON and return it to the client image.png
  • Read more about Json: https://www.w3schools.com/js/js_json_intro.asp

5. Practice MVC API

  • Create 5 APIs:
    • GET: api/categories
    • GET: api/categories/{id}
    • POST: api/categories
    • PUT: api/categories/{id}
    • DELETE: api/categories/{id}
  • Install postman to test the api: https://www.postman.com/downloads/

6. Use Javascript as frontend to call api

6. Routing in .net core

  • Routing is the process of directing URL requests to the correct controllers and actions. image.png
  • Route template
    • In order for the url request to find the correct controller action, there needs to be a template that acts as a map.
    • Example: {controller=Post}/{action=GetByIdl}/{id?}
  • There are two ways to install the route template:

7. Environment in .NET 6

  • Development: environment for developers
  • Staging: environment for testing (closer to production)
  • Production: the actual environment used by the customer.
  • Configuration in .net
    • .NET provides the appsettings.json file to store the configurations for the application.
    • For example, store ConnectionString configuration to database, application parameter information, image directory path,…. image.png
  • Configuration depends on the environment
    • appsettings.json
    • appsettings.Development.json for the development environment.
    • appsettings.Staging.json for the staging environment.
    • appsettings.Production.json for production environments.
  • launchSettings.json will rely on ASPNETCORE_ENVIRONMENT to know which environment the application is running in. image.png

8. Read the appsettings.json configuration file using IConfiguration

image.png

Refer:

Share the news now

Source : Viblo