0% found this document useful (0 votes)
26 views13 pages

Routing

The document explains routing in Asp.Net Core, detailing how incoming requests are matched to endpoints based on URLs. It describes the use of middleware methods like UseRouting() and UseEndpoints() to set up routing and how to define endpoints with various HTTP methods and parameters. Additionally, it covers route constraints, custom constraints, and the selection order of endpoints when multiple routes match a request.

Uploaded by

nasrullayev444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views13 pages

Routing

The document explains routing in Asp.Net Core, detailing how incoming requests are matched to endpoints based on URLs. It describes the use of middleware methods like UseRouting() and UseEndpoints() to set up routing and how to define endpoints with various HTTP methods and parameters. Additionally, it covers route constraints, custom constraints, and the selection order of endpoints when multiple routes match a request.

Uploaded by

nasrullayev444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Routing

Kirish

Asp.Net Coreda routing – bu kiruvchi requestni URLni tekshirib, unga mos keluvchi endpointni ishga tushirish. Misol uchun,
dasturimizda URLlar ro’yxati va ularga mos keluvchi endpointlar bor: /url1 endpoint1 ga mos kelas, /url2 endpoint2 ga mos
keladi va hokazo.

Asp.Net Core proyektimizda routingni app.UseRouting(); middleware ni ishlatish orqali ishga tushiriladi. Routelarga mos
keluvchi endpointlarni esa app.UseEndpoints() metodi bilan ko’rsatamiz. Bunda UseEndpoints() metodi ichida e’lon
qilingan lambda ifoda ichida Map bilan boshlanuvchi metodlar bilan endpointlarni ko’rsatish mumkin.

UseRouting() va UseEndPoints()

UseRouting() – routingni ishga tushiradi va HTTP metodlar va URL pathlarga qarab mos kelgan endpointlarni tanlab beradi.
app.UseRouting();

UseEndPoints() – UseRouting() metodi tomonidan tanlangan endpointni ishga tushiradi.


app.UseEndpoints(endpoints =>
{
endpoints.Map(...);
endpoints.MapGet(...);
endpoints.MapPost(...);
});

1. Endpoint.Map() da birinchi argument qilib URL beriladi, ikkinchi argumentga middleware


lambda ifoda yoki klas berish mumkin.
app.UseEndpoints(endpoints =>
{
endpoints.Map("map1", async (context) =>
{
await context.Response.WriteAsync("Map 1");
});
endpoints.Map("map2", async (context) =>
{
await context.Response.WriteAsync("Map 2");
});
});

Yuqoridagi kodni GET metod bilan ham, POST metod bilan murojaat qilib, natijani olish
mumkin. Chunki, Map() metodi barcha metodlar uchun ishlaydi.
Lekin, agar biror bir endpointni faqat bitta HTTP metod uchun ishlaydigan qilish kerak bo’lsa
nima qilinadi?
2. MapGet(), MapPost(), MapPut(), MapDelete() – HTTP metodlar uchun maxsus map
metodlar.
app.UseEndpoints(endpoints =>
{
endpoints.MapPost("map1", async (context) =>
{
await context.Response.WriteAsync("Map 1");
});
endpoints.MapGet("map2", async (context) =>
{
await context.Response.WriteAsync("Map 2");
});
});
GetEndPoint() metodi
UseRouting() metodi ishlaganda u keluvchi requestdagi URLga qarab kerakli endpointga
yo’naltiradi. Bu metod runtime paytida ishlatilganda unda enpointlar bo’yicha yetarlicha
ma’lumot bo’ladi. Ya’ni, u qaysi URL qaysi enpointga yo’naltirilishini compile paytida aniqlab
olgan. Shunday qilib, UseRouting() metodini chaqirganimizda u request URLga mos keluvchi
endpointlarni aniqlab olgan bo’ladi.
Masalan, “map1” URL kelganida UseRouting() metodi bu URLga mos kelgan birinchi endpointni
olib beradi va endpoint haqidagi ma’lumotni enpoint obyekti ko’rinishida saqlaydi. Bu endpoint
obyektini GetEndPoint() metodi yordamida olishimiz mumkin.
Eslatma: GetEndPoint() metodi yordamida biror endpointning ma’lumotini faqat UseRouting()
ishga tushganidan keyin olishimiz mumkin. Chunki, UseRouting() ishga tushmaguncha
endpointlar haqida ma’lumotlar shakllantirilmagan bo’ladi. Agar GetEndPoint() metodini
UseRouting() metodidan oldin ishlatsak, u null qaytaradi.
//...
app.Use(async (context, next) =>
{
Microsoft.AspNetCore.Http.Endpoint endpoint1 = context.GetEndpoint(); // null qaytadi
await next();
});

app.UseRouting();

app.Use(async (context, next) =>


{
Microsoft.AspNetCore.Http.Endpoint endpoint2 = context.GetEndpoint(); // endpoint obyekti qaytadi
await next();
});
//...

Endpoint obyektining ikkita muhim propertysi bor: DisplayName va RequestDelegate. Bu yerda


DisplayName URLga teng bo’ladi. RequestDelegate esa ishlatilishi kerak bo’lgan
endpointimizning o’zi hisoblanadi.
Xulosa qilib aytganda, agar bizga runtime paytida chaqirilgan endpoint bilan ishlashimiz kerak
bo’lib qolsa, bu endpoint obyektini GetEndPoint() metodi yordamida olishimiz mumkin bo’ladi.
Bu metoddan, misol uchun, keluvchi so’rovlarning qaysi endpointlarga kelishini loglashda yoki
aynan bitta endpointga keluvchi requestni filterlab olib kuzatishda foydalanish mumkin.
Route parametrlari
Quyidagi ikki xil URL uchun kod yozaylik:
 /files/sample.txt – faylni berishi kerak
 /employee/profile/alisher – xodim haqida ma’lumot beradi.
Routingda parameter qabul qilishda URLga {parameter_nomi} ko’rinishida berib qo’yiladi. Misol
uchun, fayl nomini parameterdan olish uchun /files/{file_name}.txt ko’rinishida URL beriladi.
Xodim ma’lumotlarini olishda ham xuddi shunday ko’rinishda parameter beriladi:
/employee/profile/{employee_name}
Masalan:
//...
app.UseEndpoints(endpoints =>
{
endpoints.Map("files/{filename}.{extension}", async context =>
{
await context.Response.WriteAsync("Downloading file...");
});
});
//...

HttpContext-dan paramterlarni context.Request.RouteValues yordamida ham ko’rish mumkin. Misol


uchun, tepadagi misoldagi filename parametrini context.Request.RouteValues["filename"] ko’rinishida
olsa bo’ladi.

Routening Default parametrlari


URLdagi parametrga qiymat berib yuborilmaganda unga default qiymat berib qo’yish ham
mumkin. Buning uchun figurali qavs ichida tenglik bilan default qiymat beriladi.
//...
app.UseEndpoints(endpoints =>
{
endpoints.Map("files/{filename}.{extension=txt}", async context =>
{

await context.Response.WriteAsync("Downloading file...");


});
});
//...
Ixtiyoriy parametlar
Ayrim holatlarda parametrlarni kiritishni ixtiyoriy qilish kerak bo’ladi. Misol uchun, sahifadagi
mahsulotlar ro’yxatidan biror mahsulotni qidirishda yoki shunchaki kerakli mahsulotlar to’plamini
filterlashda.
Paramterni kiritishni ixtiyoriy qilish uchun parameter nomidan keyin so’roq belgisini (?) qo’yish
kerak bo’ladi:
//...
app.UseEndpoints(endpoints =>
{
endpoints.Map("products/list/{category?}", async context =>
{
string? category = (string?)context.Request.RouteValues["Category"];
await context.Response.WriteAsync($"Products in {category}");
});
});
//...

Ixtiyoriy parametrlarga qiymat berilmaganda default null qiymatni oladi.


Real proyektda yozilishi mumkin bo’lgan kod:
//...
app.UseEndpoints(endpoints =>
{
endpoints.Map("products/list/{category?}", async context =>
{
if (context.Request.RouteValues.ContainsKey("category"))
{
string? category = (string?)context.Request.RouteValues["Category"];
await context.Response.WriteAsync($"Products in {category}");
} else
{
await context.Response.WriteAsync("Category name not given");
}
});
});
//...
Route Constraints (Route cheklovlari)
Parametr sifatida har qanday belgilarni qabul qilish mumkin. Lekin real proyektlarda parameter
qabul qilishda ba’zi cheklovlarni kiritish kerak bo’ladi. Misol uchun, electron pochta yoki ism
kiritishda to’g’ri kelgan qiymatni qabul qilib bo’lmaydi. Ya’ni, electron pochtaga Alisher ismini,
ism parametri uchun [email protected] ni qabul qilib bo’lmaydi.
Asp.Net Core da parametrlarni tekshirish imkoniyati mavjud. Bunda tekshirishni routingni o’zi
bajaradi.
Agar parameter berilgan tekshiruvga mos kelsa, shu URLga tegishli endpoint ishga tushiriladi, aks
holda keyingi routelar bilan solishtirishda davom etiladi.

Misol uchun, id parametrini validation qilaylik:


//...
endpoints.Map("products/details/{id:int}", async context =>
{
int id = (int)context.Request.RouteValues["id"];
await context.Response.WriteAsync($"Product ID: {id}");
});
//...

Bu misolda, id parametri int qiymatlarni qabul qilishini ko’rsatyapmiz: {id:int}


Validationlar
int
datetime
bool
decimal
long
guid
minlength(value) Belgilar sonini tekshiradi
maxlength(value) Belgilar sonini tekshiradi
length(min,max) Belgilar sonini tekshiradi
min(value) Teng yoki katta integer qiymatlarni tekshiradi
max(value) Teng yoki kichik integer qiymatlarni tekshiradi
range(min,max) Berilgan oraliqdagi integer qiymatlarni
tekshiradi
alpha A-Z va a-z belgilar berilganini tekshiradi.
regex(ifoda) Regular expression bilan tekshiradi.

Guid ga misol:
//...
endpoints.Map("cities/{cityid:datetime}", async context =>
{
Guid cityId = Guid.Parse(Convert.ToString(context.Request.RouteValues["cityid"])!); // ! ixtiyoriy degani
await context.Response.WriteAsync($"City info - {cityId.ToString()}");
});
//...

Minlength ga misol:
endpoints.Map("employee/profile/{EmployeeName:minlength(3)}", async context =>
{
string? employeeName = Convert.ToString(context.Request.RouteValues["employeename"]);
await context.Response.WriteAsync($"Employee info - {employeeName}");
});

Minlength va maxlength validationlarni birgalikda qo’llash:


endpoints.Map("employee/profile/{EmployeeName:minlength(3):maxlength(6)}", async context =>
{
string? employeeName = Convert.ToString(context.Request.RouteValues["employeename"]);
await context.Response.WriteAsync($"Employee info - {employeeName}");
});

Length ga misol:
endpoints.Map("employee/profile/{EmployeeName:length(3,6)}", async context =>
{
string? employeeName = Convert.ToString(context.Request.RouteValues["employeename"]);
await context.Response.WriteAsync($"Employee info - {employeeName}");
});

Regex ga misol:
endpoints.Map("sales-report/{year:int:min(1900)}/{month:regex(^(apr|jul|oct|jan)$)}", async context =>
{
int year = Convert.ToInt32(context.Request.RouteValues["year"]);
string month = (string)context.Request.RouteValues["month"];
await context.Response.WriteAsync($"sales report - {year} - {month}");
});
Custom Route Constraints
Ba’zi hollarda murakkab route cheklovlarini, masalan, regex bilan yozilganlari, ko’p joyda
ishlatishga to’g’ri keladi. Mana shu holatda duplikat bo’lishning oldini olish uchun uni alohida
klas ko’rinishida olib chiqiladi.
Custom constraint klasning umumiy ko’rinishi quyidagicha bo’ladi.
Constraint Class:
public class CustomContraint : IRouteConstraint
{
public bool Match(HttpContext? httpContext, IRouter? route,
string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true or false
}
}

Match() metodining paramtrlari:


 httpContext – HTTP request obyekti
 route – joriy routening obyekti
 routeKey – validation qilinayotgan parameter nomi
 values – validation qilinayotgan parameter qiymati. Dictionary tipida ekanligiga sabab,
parametrda birdan ko’p qiymatlarni ham olishi mumkin.
 routeRedirection -
Keyin bu klas Program.cs faylida proyektga qo’shiladi:
//...
builder.Services.AddRouting(options =>
{
options.ConstraintMap.Add("custom_contraint", typeof(CustomContraint));
});
//...

Endi oldingi darsda yozilgan /sales-report/{year}/{month} URLimizni oyini tekshiradigan kod


yozamiz:
MothConstraint klasi:
using System.Text.RegularExpressions;

namespace RoutingExample.Request
{
public class MonthConstraint : IRouteConstraint
{
public bool Match(HttpContext? httpContext, IRouter? route,
string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (!values.ContainsKey(routeKey))
{
return false;
}

Regex regex = new Regex("^(apr|jul|oct|jan)$");

string? monthValue = Convert.ToString(values[routeKey]);

return regex.IsMatch(monthValue);
}
}
}
Custom constraint klasimizni proyektimizga bog’laymiz:
//...
builder.Services.AddRouting(options =>
{
options.ConstraintMap.Add("months", typeof(MonthConstraint));
});
//...

Endi, custom constraintni routeda ishlatamiz:


//...
endpoints.Map("sales-report/{year:int:min(1900)}/{month:months}", async context =>
{
int year = Convert.ToInt32(context.Request.RouteValues["year"]);
string month = (string)context.Request.RouteValues["month"];
await context.Response.WriteAsync($"sales report - {year} - {month}");
});
//...

EndPoint ni tanlash tartibi**


Routingda requestda kelgan URL bilan routeda berilgan URLlar solishtirilib, mos kelganining
endpointi tanlanishini (yo’naltirilishini) bilib oldik. Endi, endpointlarni tanlash tartibi qanday
bajarilishini ko’ramiz.
Avvalo bir savolni ko’raylik. Agar biror requestda kelgan URL bir nechta routega mos kelsa,
qaysi route olinadi? Birinchisimi yoki ikkinchisi yoki undan keyingisi? Bunga javob qaysi route
ustun deb hisoblansa o’shanisi tanlanadi.
Bunda asosan 4 ta qoida ishlaydi:
1. Bir nechta qismdan iborat bo’lgan URL kamrog’idan ustun hisoblanadi. M: “a/b/c/d”
“a/b/c”dan ko’ra ustun hisoblanadi.
2. O’zgarmas (literal) matnli URLlar parametrli URLlardan ko’ra ustunroq. M: “a/b”
“a/{parameter}” dan ko’ra ustunroq hisoblanadi.
3. Constraintga (cheklovga) ega URL ega emasidan ko’ra ustunroq. M: “a/b:int” “a/b” dan
ko’ra ustun hisoblanadi. Yoki, masalan, “a/{b}:int” “a/b”dan ustun. Agar birinchi URLdagi
b parameter qiymati int bo’lmasa, keying routega o’tadi.
4. Barcha parametrlarni qabul qiluvchi URL (**). M: “a/{b}” “a/**” dan ko’ra ustunroq
hisoblanadi.
Misol:
//...
endpoints.Map("sales-report/{year:int:min(1900)}/{month:custom_constraint}", async context =>
{
int year = Convert.ToInt32(context.Request.RouteValues["year"]);
string month = (string)context.Request.RouteValues["month"];
await context.Response.WriteAsync($"sales report - {year} - {month}");
});

endpoints.Map("sales-report/2024/jan", async context =>


{
await context.Response.WriteAsync("Static sales report");
});
//...

Agar /sales-report/2024/jan URLi kelsa, shu ketma ketlikdagi routelarning ikkinchisi tanlanadi,
chunki u literal matn bilan yozilgan.
WebRoot va UseStaticFiles() metodi
Har qanday web proyektda pdf, css, rasm kabi static fayllar bo’lishi mumkin. Asp.Net Coreda
default holatda static fayllar bilan ishlab bo’lmaydi. Bunday fayllar bilan ishlash uchun
UseStaticFiles() middlewareini proyektga biriktirish kerak.
Mijoz serverdan biror faylni so’rab request jo’natganda, UseStaticFiles() middleware WebRoot
papkasida so’ralgan fayl borligini tekshiradi, agar bo’lsa faylni responsega qo’shib qaytaradi, aks
holda 404 statusli response qaytaradi.
Default holatda WebRoot papkasi wwwroot papka hisoblanadi. Lekin, boshqa papkani ham
WebRoot papka sifatida belgilash mumkin. Shuningdek, bir nechta papkani ham ko’rsatib qo’yish
mumkin.
WebRoot papkaga browser to’g’ridan to’g’ri murojaat qila olishi kerak. Chunki, shundagina u
serverdan static fayllarni olishi mumkin bo’ladi.
Asp.Net ning eski versiyalarida proyektning barcha fayllariga (kod yozilgan fayllarga ham)
tashqaridan murojaat qilish mumkin bo’lgan. Bu esa xavfsizlik jihatdan noto’g’ri hisoblanadi. Bu
muammoni oldini olish uchun WebRoot papkasi tushunchasi qo’shildi. Tashqaridan faqat
WebRoot papkaga murojaat qilish mumkin.
UseStaticFiles() middlewareini proyektga biriktirgandan keyin, browserdan turib, wwwroot
papkasidagi static fayllarga murojaat qilishimiz mumkin bo’ladi:

WebRoot papkasi nomini o’zgartirish


wwwroot papkasini boshqa nomga o’zgartirish uchun WebApplication.CreateBuilder()
konstruktorida WebApplicationOptions obyekti bilan ko’rsatamiz. Masalan, wwwroot papkasini
myroot ga o’zgartirmoqchimiz:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
WebRootPath = "myroot"
});

Endi, UseStaticFiles() middlewarei myroot papkasidan static fayllarni qidiradi (bazi sabablarga
ko’ra, ya’ni xatolik chiqmasligi uchun wwwroot nomli papkani ham qoldiramiz).
Bir nechta WebRoot papka bilan ishlash
Misol uchun bizga myroot papkasidan tashqari, static fayllar uchun assets papkasi ham kerak
bo’ldi. Qo’shimcha WebRoot papkasini qo’shish uchun yana bitta UseStaticFiles() middlewareini
ishlatishimiz kerak bo’ladi.
//...
app.UseStaticFiles(); // myroot (default wwwroot) bilan ishlovchi middleware
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, "\\assets")
)
});
//...

Yuqoridagi koddagi builder.Environment.ContentRootPath joriy ishlab turgan papkani, ya’ni biz kod
yozayotgan Program.cs fayl turgan papkani ko’rsatadi.
Browser faylni so’rab serverga murojaat qilganda, fayl avval asosiy myroot (default wwwroot)
papkadan, u yerdan fayl topilmasa, keyin assets papkasidan qidiriladi.
Attribute routing va conventional routing
Savol va javoblar:
1. Routing nima?

Routing is functionality that map incoming request to the route handler. The route can have route parameters to
receive values from the URL. Using the route, routing can find a route handler based on the URL. All the routes
are registered when the application is started. There are two types of routing supported by ASP.NET Core

1. The conventional routing


2. Attribute routing

The Routing uses routes to map incoming requests with the route handler and Generates URL that is used in
response. Mostly, the application has a single collection of routes and this collection is used for the process of the
request. The RouteAsync method is used to map incoming requests (that match the URL) with available in route
collection.

2. ASP.NET Core da routing qanday ishlaydi?

Routing is used to handle incoming HTTP requests for the app. Routing finds matching executable endpoint for
incoming requests. These endpoints are registered when app starts. Matching process use values from incoming
request url to process the requests. You can configure the routing in middleware pipeline of configure method in
startup class.

app.UseRouting(); // It adds route matching to middleware pipeline

// It adds endpoints execution to middleware pipeline


app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});

});

3. Qachon conventional routing o’rniga attribute routingdan foydalangan yaxshi?

In ASP.NET Core, you can define routes for your web application using either attribute routing or conventional
routing. The choice between the two depends on the complexity and requirements of your application. Here are
some scenarios where you might prefer attribute routing over conventional routing:

- Fine-grained control: Attribute routing allows you to define routes directly on the action methods or
controllers using attributes. This gives you more granular control over the routing behavior for specific
actions. You can have different routes for different actions, making it easier to manage and understand the
routing logic.
- Controller-specific routes: With attribute routing, you can define routes specific to a controller by placing
the routing attributes directly on the controller class. This is useful when you have actions that share a
common route prefix, simplifying the route definitions.
- Action-specific routes: In some cases, you may want to have multiple routes for a single action method.
Attribute routing allows you to define additional routes for an action by adding multiple attributes on the
same method.
- Complex routing requirements: If your application has complex routing requirements, attribute routing can
provide a more straightforward and concise way to handle those scenarios. You can use route parameters,
optional segments, and custom route constraints directly in the attribute, making the routing logic more
readable.
On the other hand, conventional routing can be more suitable for simpler applications with straightforward routing
requirements. It relies on the route template defined in the Startup class, which makes it easier to see all the routes
at once. It's a good choice when your application has a small number of routes and doesn't require fine-grained
control over individual actions.

4. Route constraintlar nega kerak?

In ASP.NET Core, route constraints are used to restrict the values that can be matched for route parameters. They
are an essential part of defining more specific and controlled routes. Here are some important route constraints you
can use:

 int: Constrains the parameter to be an integer.


 long: Constrains the parameter to be a long integer.
 bool: Constrains the parameter to be a Boolean value, i.e., "true" or "false".
 double: Constrains the parameter to be a double-precision floating-point number.
 float: Constrains the parameter to be a floating-point number.
 guid: Constrains the parameter to be a GUID (Globally Unique Identifier).
 datetime: Constrains the parameter to be a valid date and time value.
 alpha: Constrains the parameter to contain only letters (no digits or special characters).
 regex: Allows you to define a custom constraint using a regular expression pattern.
 length: Constrains the parameter to have a specific length. For example, {id:length(5)} will only match
when the id parameter has a length of 5 characters.
 min and max: Allows you to specify minimum and maximum values for numeric parameters. For
example, {age:min(18)} will only match if the age parameter is 18 or greater.
 range: Similar to min and max, but allows you to specify a range of values. For example,
{year:range(1900, 2023)} will only match if the year parameter is between 1900 and 2023.
 required: Indicates that the parameter is required and must be present in the URL for the route to match.
 nonempty: Ensures that the parameter is not empty (not null, empty string, or whitespace).
 maxlength and minlength: Restricts the length of a string parameter. For example,
{username:maxlength(20)} will only match if the username parameter has a length of 20 characters or
less.

5. wwwroot papkasi nima maqsadda ishlatiladi?

The wwwroot folder is a special folder in an ASP.NET Core web application that serves as the web root. Its
purpose is to store static files, such as HTML, CSS, JavaScript, images, and other client-side assets that need to be
directly accessible by the web browser.

When a web application receives a request, the web server looks for the requested resource within the wwwroot
folder. If the resource is found in this folder, the web server serves it directly to the client without involving the
ASP.NET Core middleware pipeline.

6. wwwroot papkasini qanday qilib o’zgartirsa bo’ladi?

We need to set path of the wwwroot folder in the WebRootPath propertyof the WebApplicationOptions class.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions()


{
WebRootPath = "foldername"
});

You might also like