كيفية استدعاء Web API في ASP.NET Core
-
تعلمنا سابقا كيفية إنشاء Web APIs في ASP.NET Core [نمط RESTful] حيث قمنا بإنشاء Web API لقراءة المواد من قاعدة البيانيات وأيضا انشانا API لإضافة مادة جديدة.
لكن كيف يمكن نستفيد من هذا API وكيف ممكن نستخدمو.
سنقوم الآن باستدعاء (API) في مشروع آخر.
سنعمل على انشاء مشروع جديد خاص للطلاب بنسميه CustomerPortal
يمكن للطالب في هاذ Portal من عرض المواد الي بتكون موجوده ومتوفرة.
للتذكير ايش هي API؟
API تعني (Application Programming Interface) وهي واجهة او طريقة يمكن من خلالها للعديد من التطبيقات بالتواصل مع بعضها البعض. نستخدم API يوميًا مثل:
⦁ تحديث الطقس الحالي لمنطقتنا على الهاتف.
⦁ وأسعار الأسهم الحالية ، وما إلى ذلك.
⦁ تطبيقات حجز السفر ، من خلال هذه التطبيقات ممكن نوصل لأكثر من شركة طيران.
بنقدر نقول ان API ممكن نوصل ليها عن طريق عن URL
الان نوخذ فكرع عن شو هو استدعاء API؟
API هو خدمه تم برمجتها بحيث يؤدي العمل الذي تم تصميمه من أجله. يعني بنطلب API حتي نحصل على نتيجة، بعد ما نطلب API بتكون النتيجة اذا تم التنفيذ بيرسل حالة العمل المكتمل ، في حالة حدوث خطأ ، يتم إرجاع رمز الخطأ المناسب والرسالة مرة أخرى(اذا بتذكر حكينا سابقا عن رموز الأخطاء الىي ممكن ترجع).
حتى نستخدم هذا API لازم نعرف وين مكان الاستخدام المناسب. إذا كنت مطور تطبيقات اكيد الاستخدام بكون داخل تطبيقك، إذا كنت مستخدم عادي بكون حسب الخدمة المطلوبة (ارجع للأمثلة السابقة)
وبما ان الهدف في هذا الدرس نتعلم كيف ممكن نستخدم API في التطبيقات، لذا سنبدأ بإنشاء مشروع جديد
ملاحظة :
حكينا بالسابق عن ان API يعمل مع الطرق التي تستدعيها HTTP protocols. وهاذي الطرق يطلق عليها GET ، PUT ، POST ، و DELETE وهي الأكثر شيوعًا.
خلينا نبدأ بإنشاء مشروع جديد في 2022 Visual Studio ونسميه StudentPortal ويكون نوع المشروع
Model-View-Controller))ASP.Net Core Web App )
بنستخدم تصميم MVC في هذا المشروع ، الهدف عرض البيانات الي بترجع من API في View، واكيد لازم تكون لغة البرمجة #C بعدها Next
من الشاشة التالية نختار اسم المشروع StudentPortal ومكان التخزين وبعدها Next ،
بعدها نختار Framework والي بتكون 6.0 وما بنغير اشي من باقي الإعدادات واكيد بعدا نختار Create
ننتظر شوي حتي يتم انشاء التطبيق وبتكون النتيجة
طيب الأمور لحد الان تمام.
الان صار دور نفكر بشو بدنا نعرض في الصفحة View ، وبما ان الهدف نستخدم API الي عملنا سابقا وكان برجع المواد المتوفرة يعني الهدف استدعاء هذا API وعرض المواد في View
تمام بناء على هذا الكلام نحنا بحاجة نعمل model حتي نستقبل البيانات الي بترجع
طيب ننقل الى مجلد Models وخلينا نضيف class باسم CoursesModel وبنظيف الكود التالي اليه
public class CoursesModel
{
public int CoursesId { get; set; }
public string CourseNumber { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public decimal Price { get; set; }
public int Capacity { get; set; }
}
@using StudentPortal
@using StudentPortal.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers



public async Task<ActionResult<IEnumerable<CoursesModel>>> GetCoursesModel()

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using StudentPortal.Models;
namespace StudentPortal.Controllers
{
public class CourseController : Controller
{
public async Task<IActionResult> Index()
{
List<CoursesModel> CoursesList = new List<CoursesModel>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:7081/api/Course/GetAllCourses"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
CoursesList = JsonConvert.DeserializeObject<List<CoursesModel>>(apiResponse);
}
}
return View(CoursesList);
}
}
}
List<CoursesModel> CoursesList = new List<CoursesModel>();
var response = await httpClient.GetAsync("https://localhost:7081/api/GetAllCourses")
JsonConvert.DeserializeObject<List<CoursesModel>>(apiResponse);





@model IEnumerable<CoursesModel>
@{ Layout = "_Layout"; ViewBag.Title = "All Courses";}
<h2>All Courses</h2>
<a asp-action="AddCourse" class="btn btn-sm btn-primary">Add Courses</a>
<a asp-action="GetCourse" class="btn btn-sm btn-secondary">Get Courses</a>
<table class="table table-sm table-striped table-bordered m-2">
<thead>
<tr>
<th>Course ID</th>
<th>CourseNumber</th>
<th>CourseName</th>
<th>CourseDescription</th>
<th>Price</th>
<th>Capacity</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach (var C in Model)
{
<tr>
<td>@C.CoursesId</td>
<td>@C.CourseNumber</td>
<td>@C.CourseName</td>
<td>@C.CourseDescription</td>
<td>@C.Price</td>
<td>@C.Capacity</td>
<td>
<a asp-action="UpdateReservation" asp-route-id="@C.CoursesId">Edit
@*<img src="/icon/edit.png" />*@
</a>
</td>
<td>
<form asp-action="DeleteReservation" method="post">
<input type="hidden" value="@C.CoursesId" name="CoursesId" />
<input type="button" value="Delete" class="btn btn-danger">
@* <input type="image" src="/icon/close.png" />*@
</form>
</td>
</tr>
}
</tbody>
</table>

@model IEnumerable<CoursesModel>
<thead>
<tr>
<th>Course ID</th>
<th>CourseNumber</th>
<th>CourseName</th>
<th>CourseDescription</th>
<th>Price</th>
<th>Capacity</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
public ViewResult GetCourseByID() => View();
[HttpPost]
public async Task<IActionResult> GetCourseByID(int id)
{
List<CoursesModel> CoursesList = new List<CoursesModel>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:7081/api/Course/GetCoursesById?id=" + id))
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string apiResponse = await response.Content.ReadAsStringAsync();
CoursesList = JsonConvert.DeserializeObject<List<CoursesModel>>(apiResponse);
}
else
ViewBag.StatusCode = response.StatusCode;
}
}
return View(CoursesList);
}
@model IEnumerable<CoursesModel>
@{ Layout = "_Layout"; ViewBag.Title = "Get Course by Id";}
<h2>Get Course by Id </h2>
<h3>@ViewBag.StatusCode</h3>
<form method="post">
<div class="form-group">
<label for="id">Course Id:</label>
<input class="form-control" name="id" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-sm btn-secondary">Get Course Details</button>
</div>
</form>
@if (Model != null)
{
<h2>Course Details</h2>
<table class="table table-sm table-striped table-bordered m-2">
<thead>
<tr>
<th>Course ID</th>
<th>CourseNumber</th>
<th>CourseName</th>
<th>CourseDescription</th>
<th>Price</th>
<th>Capacity</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach (var C in Model)
{
<tr>
<td>@C.CoursesId</td>
<td>@C.CourseNumber</td>
<td>@C.CourseName</td>
<td>@C.CourseDescription</td>
<td>@C.Price</td>
<td>@C.Capacity</td>
<td>
<a asp-action="UpdateReservation" asp-route-id="@C.CoursesId">Edit
@*<img src="/icon/edit.png" />*@
</a>
</td>
<td>
<form asp-action="DeleteReservation" method="post">
<input type="hidden" value="@C.CoursesId" name="CoursesId" />
<input type="button" value="Delete" class="btn btn-danger">
@* <input type="image" src="/icon/close.png" />*@
</form>
</td>
</tr>
}
</tbody>
</table>
}

public ViewResult AddCourses() => View();
[HttpPost]
public async Task<IActionResult> AddCourses(CoursesModel coursesModel)
{
CoursesModel receivedCoursesModel = new CoursesModel();
using (var httpClient = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(coursesModel), Encoding.UTF8, "application/json");
using (var response = await httpClient.PostAsync("https://localhost:7081/api/Course/AddCourses", content))
{
}
}
return Redirect("Index");
}


return Redirect("Index");

اترك تعليقك