ASP.NET Core Convention-Based URL Routing
-
يتم استخدام ASP.NET Core URL Routing لإنشاء URL patterns للتطبيق الخاص بك. حيث يعمل على مطابقة طلبات HTTP الواردة ويرسل تلكالطلبات إلى application’s endpointss. و Endpoints هي تلك الوحدات المسؤولة عن معالجة الطلب. يتم تحديد هذه الطلبات داخل Configure() method في Startup.cs class.
يحتوي Routing System على وظيفتين رئيسيتين:
- تعيين عناوين incoming URLs إلى Controllers and Actions.
- يقوم بإنشاء عناوين outgoing URLs بحيث يتم استدعاء specific action method عندما ينقر المستخدم فوق link.
هناك طريقتان لإنشاء routes في ASP.NET Core:
- Convention-Based Routing (ما سيتم تناوله في هذا الدرس)
- Attribute-Based Routing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace StudentsAcademy
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
// Default route
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StudentsAcademy.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using StudentsAcademy.Services;
using StudentsAcademy.Share;
namespace StudentsAcademy.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
أضفنا أيضًا view باسم Index داخل Views ➤ Home Folder.
غير الكود في View الى:
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<title>Routing</title>
</head>
<body>
<h1>Home Controller, Index View</h1>
</body>
</html>
https://localhost:44382/

تمام خلونا نبدا بشرح الأجزاء الموجودة segments في URLs قبل البدء بشرح كيفية عمل URL Routing.
ما هي Segment في URL
Segmentsهي أجزاء من عنوان URL ، باستثناء hostname و query string ، ويتم الفصل بينها بالرمز "/".
توضح الصورة المقدمة ما هي الأجزاء:
يمكن أن يحتوي عنوان URL على 0 جزء أو أجزاء لا نهائية ولكن معظم التطبيقات لا تحتاج إلى أكثر من 3 أجزاء.
عندما يكون هناك طلب HTTP، فإن مهمة نظام التوجيه Routing System هي فحص عنوان URL واستخراج segments values منه.
يتم تحديد المسار الافتراضي في ()Configure الموجوده في Startup.cs class، ويعمل Net Core. تعريف افتراضي للمسار حيث تم تحديد المسار الافتراضي default route ("default" هو مجرد اسم ويمكن أن يكون أي اسم ثاني).
داخل هذه method استخدمنا UseEndpoints الذي يستخدم لإنشاء مسار واحد a single route، وعملنا اضافة Endpoints ل Controller’s action. لهذا استخدمنا ()MapControllerRoute .
يُطلق على المسار الفردي اسم default route.
الكود:
app.UseEndpoints(endpoints =>
{
// Default route
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
- {controller=Home} تشير الى اسم controller الافتراضي.
- {action=Index} يشير الى Action الافتراضي.
- {id?} يشير الى Parameter ، الإشارة ? تعني ان هذا Parameter اختياري.
https://localhost:44382/
https://localhost:44382/Home/Index
- ‘Home’ for the controller
- ‘Index’ for action.
Maps to | URL | Segments |
controller = Home action = Index | / | 0 |
controller = Home action = Index | /Home | 1 |
controller = About action = Index | /About | 1 |
controller = Home action = Index | /Home/Index | 2 |
controller = Home action = List | /Home/List | 2 |
controller = About action = Show | /About/Show | 2 |
controller = About action = Index | /Home/Index/3 | 3 |
No match | /Home/List/3 | 3 |
app.UseEndpoints(endpoints =>
{
// Default route
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}");
});

URL - https://localhost:44382/Home/Index
Maps to | URL | Segments |
No match | / | 0 |
No match | /Home | 1 |
controller = Home action = Index | /Home/Index | 2 |
controller = Home action = List | /Home/List | 2 |
controller = About action = List | /About/List | 2 |
No match | /Home/Show/4 | 3 |
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "news1",
pattern: "News/{controller=Home}/{action=Index}");
});
pattern: "News/{controller=Home}/{action=Index}");
URL - https://localhost:44382/News.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "news2",
pattern: "News{controller}/{action}");
});
URL - https://localhost: 44382/NewsHome/Index.

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "shop",
pattern: "Shopping/{action}",
defaults: new { controller = "Home" });
});
URL - https://localhost:44382/Shopping/Index

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "old",
pattern: "Shopping/Old",
defaults: new { controller = "Home", action = "Index" });
});
– https://localhost:44382/Shopping/Old.

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "old",
pattern: "Shopping/Old",
defaults: new { controller = "Home", action = "Index" });
endpoints.MapControllerRoute(
name: "shop",
pattern: "Shopping/{action}",
defaults: new { controller = "Home" });
});
public IActionResult Old ()
{
return View();
}
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<title>Routing</title>
</head>
<body>
<h1>Home Controller, Old View</h1>
</body>
</html>
URL - https://localhost:44382/Shopping/Old

URL https://localhost:44382/Shopping/Old
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "shop",
pattern: "Shopping/{action}",
defaults: new { controller = "Home" });
endpoints.MapControllerRoute(
name: "old",
pattern: "Shopping/Old",
defaults: new { controller = "Home", action = "Index" });
});
https://localhost:44382/Shopping/Old

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "shop",
pattern: "Shopping/{action}",
defaults: new { controller = "Home" });
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyRoute",
pattern: "{controller=Home}/{action=Index}/{id}");
});
public IActionResult Check()
{
ViewBag.ValueofId = RouteData.Values["id"];
return View();
}
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<title>Routing</title>
</head>
<body>
<h1>Home Controller, Check View</h1>
<h2>Id value is: @ViewBag.ValueofId</h2>
</body>
</html>
https://localhost:44382/Home/Check/cSharp

URL - https://localhost:58470/Home/Check

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyRoute",
pattern: "{controller=Home}/{action=Index}/{id}");
});
public IActionResult Check(int id)
{
ViewBag.ValueofId = id;
return View();
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyRoute1",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
public IActionResult Check()
{
ViewBag.ValueofId = RouteData.Values["id"];
return View();
}
https://localhost:58470/Home/Check
public IActionResult Check(string id)
{
ViewBag.ValueofId = id ?? "Null Value";
return View();
}
ViewBag.ValueofId = id ?? "Null Value"
URL - https://localhost:58470/Home/Check.
http://localhost: 58470/Home/Check/Hello/World
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyRoute2",
pattern: "{controller=Home}/{action=Index}/{id?}/{idtwo?}");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MyRoute2",
pattern: "{controller=Home}/{action=Index}/{id?}/{*catchall}");
});
Maps to | URL | Segments |
controller = Home action = Index id = Null | / | 0 |
controller = Home action = Index id = Null | /Home | 1 |
controller = Home action = CatchallTest Id = Null | /Home/CatchallTest | 2 |
controller = Home action = catchallTest id = Hello | /Home/CatchallTest/Hello | 3 |
controller = Home action = catchallTest id = Hello catchall = How | /Home/CatchallTest/Hello/How | 4 |
controller = Home action = catchallTest id = Hello catchall = How/Are | /Home/CatchallTest/Hello/How/Are | 5 |
controller = Home action = catchallTest id = Hello catchall = How/Are/You | /Home/CatchallTest/Hello/How/Are/U | 6 |
public IActionResult CatchallTest(string id, string catchall)
{
ViewBag.ValueofId = id;
ViewBag.ValueofCatchall = catchall;
return View();
}
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<title>Routing</title>
</head>
<body>
<h1>@@#Home@@# Controller, @@#CatchallTest@@# View</h1>
<h2>Id value is: @ViewBag.ValueofId</h2>
<h2>Catchall value is: @ViewBag.ValueofCatchall</h2>
</body>
</html>
URL - http://localhost:58470/Home/CatchallTest/Hello/How/Are/U.
اترك تعليقك