The main objectives of this article are:
Now add a route for our 'BeachList.vue' vue component.
Refer:
- Create A HTTP GET API Endpoint To Fetch All Data
- Create Vue Component To Display All Data
Create A 'Beach' Controller In The API Project:
A Controller is an entity or class that contains a logical method or function that gets executed for an HTTP request from the clients.
Let's create a controller 'BeachController.cs'.
API_Project/Controllers/BeachController.cs:
using Dot7.API.CRUD.Data; using Microsoft.AspNetCore.Mvc; namespace Dot7.API.CRUD.Controllers; [ApiController] [Route("[controller]")] public class BeachController:ControllerBase { private readonly MyWorldDbContext _myWorldDbContext; public BeachController(MyWorldDbContext myWorldDbContext) { _myWorldDbContext = myWorldDbContext; } }
- (Line: 6) The 'ApiController' attribute applies all API rules to the controller.
- (Line: 7) The 'Route("[controller]")' attribute enables the attribute routing for the controller. The '[controler]' expression represents the name of the controller that will be part of the URL.
- (Line: 8) To make our 'BeachController' class an API controller it must inherit the 'ControllerBase'.
- (Line: 10-14) Injected our database context into our controller constructor.
Create HTTP GET Endpoint Action Method In API Project:
In an API the action method is the logic unit that gets executed for the HTTP request and serves the response to the users.
Let's create the action method to implement the Read Operation.
API_Project/Controllers/BeachController.cs:
using Microsoft.EntityFrameworkCore; [HttpGet] public async Task<IActionResult> Get() { var beaches = await _myWorldDbContext.Beach.ToListAsync(); return Ok(beaches); }
- (Line: 3) The 'HttpGet' attribute makes our action method invoked only for HTTP GET requests.
- (Line: 6) The 'ToListAsync()' method fetches all records from the database asynchronously.
- (Line: 7) The 'Ok()' method returns the success response.
To test our endpoint, let's insert some data into the database and then run our API project and check the swagger page output.
Create A 'BeachList' Vue Component In VueJs Application:
Let's create a vue component like 'BeachList.vue' at 'src/views/beaches'(new folder)
Vue_Project/src/router/index.js:
import { createRouter, createWebHistory } from 'vue-router' import BeachList from '../views/beaches/BeachList.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: BeachList } ] }) export default router
- (Line: 7-9) Here home route configured for the 'BeachList' vue component
Install Axios Library Into Vue Application:
To invoke the HTTP API calls one of the best-recommended third-party libraries is Axios.
npm i axios
Consume HTTP Get Endpoint From 'BeachList' Vue Component:
Let's try to invoke the HTTP GET Endpoint from the 'BeachList' vue component and then render the API response.
src/views/beaches/BeachList.vue:
<script setup> import { ref, onMounted } from 'vue'; import axios from 'axios' const beachCollection = ref([]); onMounted(() => { axios.get("http://localhost:5247/Beach") .then((response) => { beachCollection.value = response.data; }); }) </script> <template> <div class="container"> <div class="row row-cols-1 row-cols-md-3 g-4"> <div class="col" v-for="item in beachCollection" :key="item.id"> <div class="card"> <img :src="item.imageUrl" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ item.beachName }}</h5> <p class="card-text">Location: {{ item.place }}</p> </div> </div> </div> </div> </div> </template>
- (Line: 1) The 'setup' attribute added to the script tag that represents we are using the composition API approach.
- (Line: 4) Declared 'beachCollection' variable of type 'ref'. The 'ref' type is used to declare the reactive properties. Here 'ref([])' means empty array will be the initial value for the 'beachCollection' variable. The 'ref' imports from the 'vue' library.
- (Line: 5) The 'onMounted' is a life cycle method. Here we can add our logic that needs to be executed on the component mounted. Here generally we invoke our APIs whose response we want to display on page load.
- (Line: 6-9) Using 'axios.get()' invoking our HTTP GET API endpoint. Here API response is assigned to 'beachCollection' variable. In vue to assign value to 'ref' variable we should assign it to '{variable}.value', we can't directly assign it to the variable itself.
- (Line: 13-28) Inside of the 'template' element we have to render all our component HTML content.
- (Line: 16) The 'v-for' attribute is used to loop the HTML element based on the collection variable from the component just like 'beachCollection'. The ':key' attribute assigned with unique value like 'id' from the collection to render, this attribute helps for tracking.
- In vue to render any data dynamically or data binding we have to use '{{}}'
Enable CORS Service In API Project:
Let's enable the CORS service in our API project.
API_Project/Program.cs:
builder.Services.AddCors(options => { options.AddPolicy("Cors", p => { p.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin(); }); }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseCors("Cors"); // existing code hidden for display purpose
- (Line: 1-7) Registered the cors service, here we are allowing any kind of client application by configuring the 'AllowAnyOrignin()', but we can do the required origins allow setup if we need.
- (Line: 14) Here configured the cors middleware.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping UP:
Hopefully, I think this article delivered some useful information on the .NET 7 Web API and Vue(3.0) application. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-3 | .NET7 Web API | SQL Database | VueJS(3.0) - Composition API | CRUD Example
Part-5 | .NET7 Web API | SQL Database | VueJS(3.0) - Composition API | CRUD Example
Part-6 | .NET7 Web API | SQL Database | VueJS(3.0) - Composition API | CRUD Example
Part-5 | .NET7 Web API | SQL Database | VueJS(3.0) - Composition API | CRUD Example
Part-6 | .NET7 Web API | SQL Database | VueJS(3.0) - Composition API | CRUD Example
Comments
Post a Comment