Skip to content

Commit a2a03e4

Browse files
author
XuanThuLab
committed
Session
1 parent a4a4257 commit a2a03e4

24 files changed

+8522
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{
2+
// Use IntelliSense to find out which attributes exist for C# debugging
3+
// Use hover for the description of the existing attributes
4+
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": ".NET Core Launch (web)",
9+
"type": "coreclr",
10+
"request": "launch",
11+
"preLaunchTask": "build",
12+
// If you have changed target frameworks, make sure to update the program path.
13+
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/05.Session.dll",
14+
"args": [],
15+
"cwd": "${workspaceFolder}",
16+
"stopAtEntry": false,
17+
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18+
"serverReadyAction": {
19+
"action": "openExternally",
20+
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21+
},
22+
"env": {
23+
"ASPNETCORE_ENVIRONMENT": "Development"
24+
},
25+
"sourceFileMap": {
26+
"/Views": "${workspaceFolder}/Views"
27+
}
28+
},
29+
{
30+
"name": ".NET Core Attach",
31+
"type": "coreclr",
32+
"request": "attach",
33+
"processId": "${command:pickProcess}"
34+
}
35+
]
36+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
{
2+
"version": "2.0.0",
3+
"tasks": [
4+
{
5+
"label": "build",
6+
"command": "dotnet",
7+
"type": "process",
8+
"args": [
9+
"build",
10+
"${workspaceFolder}/05.Session.csproj",
11+
"/property:GenerateFullPaths=true",
12+
"/consoleloggerparameters:NoSummary"
13+
],
14+
"problemMatcher": "$msCompile"
15+
},
16+
{
17+
"label": "publish",
18+
"command": "dotnet",
19+
"type": "process",
20+
"args": [
21+
"publish",
22+
"${workspaceFolder}/05.Session.csproj",
23+
"/property:GenerateFullPaths=true",
24+
"/consoleloggerparameters:NoSummary"
25+
],
26+
"problemMatcher": "$msCompile"
27+
},
28+
{
29+
"label": "watch",
30+
"command": "dotnet",
31+
"type": "process",
32+
"args": [
33+
"watch",
34+
"run",
35+
"${workspaceFolder}/05.Session.csproj",
36+
"/property:GenerateFullPaths=true",
37+
"/consoleloggerparameters:NoSummary"
38+
],
39+
"problemMatcher": "$msCompile"
40+
}
41+
]
42+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
<RootNamespace>05.Session</RootNamespace>
6+
</PropertyGroup>
7+
8+
<ItemGroup>
9+
<PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" />
10+
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.7" />
11+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
12+
</ItemGroup>
13+
14+
</Project>
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
using System;
2+
using System.Linq;
3+
using System.Text;
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Http;
7+
using Newtonsoft.Json;
8+
9+
namespace _05.Session {
10+
public class ProductController {
11+
IListProductName lsPhone;
12+
IListProductName lsLaptop;
13+
14+
// Inject hai dịch vụ qua phương thức khởi tạo
15+
public ProductController (IListProductName lsphone, LaptopName lslaptop) {
16+
Console.WriteLine (this.GetType ().Name + " created");
17+
this.lsPhone = lsphone;
18+
this.lsLaptop = lslaptop;
19+
}
20+
21+
// Xuất danh sách sản phẩm cho Response
22+
public async Task List (HttpContext context) {
23+
24+
CountAccess (context);
25+
26+
var sb = new StringBuilder ();
27+
string lsPhoneHTML = string.Join ("", lsPhone.GetNames ().Select (name => name.HtmlTag ("li"))).HtmlTag ("ul");
28+
string lsLaptopHTML = string.Join ("", lsLaptop.GetNames ().Select (name => name.HtmlTag ("li"))).HtmlTag ("ul");
29+
sb.Append ("Danh sách điện thoại".HtmlTag ("h2"));
30+
sb.Append (lsPhoneHTML);
31+
32+
sb.Append ("Danh sách Laptop".HtmlTag ("h2"));
33+
sb.Append (lsLaptopHTML);
34+
35+
string menu = HtmlHelper.MenuTop (HtmlHelper.DefaultMenuTopItems (), context.Request);
36+
string html = HtmlHelper.HtmlDocument ("DS Sản phẩm", menu + sb.ToString ().HtmlTag ("div", "container"));
37+
38+
context.Response.StatusCode = 200;
39+
await context.Response.WriteAsync (html);
40+
}
41+
42+
public void CountAccess (HttpContext context) {
43+
// Lấy ISession
44+
var session = context.Session;
45+
string key_access = "info_access";
46+
47+
// Lưu vào Session thông tin truy cập
48+
// Định nghĩa cấu trúc dữ liệu lưu trong Session
49+
var accessInfoType = new {
50+
count = 0,
51+
lasttime = DateTime.Now
52+
};
53+
54+
// Đọc chuỗi lưu trong Sessin với key = info_access
55+
string json = session.GetString (key_access);
56+
dynamic lastAccessInfo;
57+
if (json != null) {
58+
// Convert chuỗi Json - thành đối tượng có cấu trúc như accessInfoType
59+
lastAccessInfo = JsonConvert.DeserializeObject (json, accessInfoType.GetType ());
60+
} else {
61+
// json chưa từng lưu trong Session, accessInfo lấy bằng giá trị khởi tạo
62+
lastAccessInfo = accessInfoType;
63+
}
64+
65+
// Cập nhật thông tin
66+
var accessInfoSave = new {
67+
count = lastAccessInfo.count + 1,
68+
lasttime = DateTime.Now
69+
};
70+
71+
// Convert accessInfo thành chuỗi Json và lưu lại vào Session
72+
string jsonSave = JsonConvert.SerializeObject (accessInfoSave);
73+
session.SetString (key_access, jsonSave);
74+
Console.WriteLine (jsonSave);
75+
}
76+
public static string CountAccessInfo (HttpContext context) {
77+
var session = context.Session; // Lấy ISession
78+
string key_access = "info_access";
79+
80+
// Lưu vào Session thông tin truy cập
81+
// Định nghĩa cấu trúc dữ liệu lưu trong Session
82+
var accessInfoType = new {
83+
count = 0,
84+
lasttime = DateTime.Now
85+
};
86+
87+
// Đọc chuỗi lưu trong Sessin với key = info_access
88+
string json = session.GetString (key_access);
89+
dynamic lastAccessInfo;
90+
if (json != null) {
91+
// Convert chuỗi Json - thành đối tượng
92+
lastAccessInfo = JsonConvert.DeserializeObject (json, accessInfoType.GetType ());
93+
} else {
94+
// json chưa từng lưu trong Session, accessInfo lấy bằng giá trị khởi tạo
95+
lastAccessInfo = accessInfoType;
96+
}
97+
if (lastAccessInfo.count == 0) {
98+
return "Chưa truy cập /Product lần nào".HtmlTag ("p");
99+
}
100+
101+
string thongtin = $"Số lần truy cập /Product: {lastAccessInfo.count} - lần cuối: {lastAccessInfo.lasttime.ToLongTimeString()}";
102+
return thongtin;
103+
}
104+
105+
}
106+
}

ASP_NET_CORE/05.Session/HtmlHelper.cs

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
using System.Collections.Generic;
2+
using Microsoft.AspNetCore.Http;
3+
using System.Text;
4+
5+
public static class HtmlHelper
6+
{
7+
/// <summary>
8+
/// Phát sinh trang HTML
9+
/// </summary>
10+
/// <param name="title">Tiêu đề trang</param>
11+
/// <param name="content">Nội dung trong thẻ body</param>
12+
/// <returns>Trang HTML</returns>
13+
public static string HtmlDocument(string title, string content) {
14+
return $@"
15+
<!DOCTYPE html>
16+
<html>
17+
<head>
18+
<meta charset=""UTF-8"">
19+
<title>{title}</title>
20+
<link rel=""stylesheet"" href=""/css/site.min.css"" />
21+
<script src=""/js/jquery.min.js"">
22+
</script><script src=""/js/popper.min.js"">
23+
</script><script src=""/js/bootstrap.min.js""></script>
24+
</head>
25+
<body>
26+
{content}
27+
</body>
28+
</html>";
29+
}
30+
31+
32+
/// <summary>
33+
/// Phát sinh HTML thanh menu trên, menu nào active phụ thuộc vào URL mà request gủi đến
34+
/// </summary>
35+
/// <param name="menus">Mảng các menu item, mỗi item có cấu trúc {url, lable}</param>
36+
/// <param name="request">HttpRequest</param>
37+
/// <returns></returns>
38+
39+
public static string MenuTop(object[] menus, HttpRequest request) {
40+
41+
var menubuilder = new StringBuilder();
42+
menubuilder.Append("<ul class=\"navbar-nav\">");
43+
foreach (dynamic menu in menus) {
44+
string _class = "nav-item";
45+
// Active khi request.PathBase giống url của menu
46+
if (request.PathBase == menu.url) _class += " active";
47+
menubuilder.Append($@"
48+
<li class=""{_class}"">
49+
<a class=""nav-link"" href=""{menu.url}"">{menu.label}</a>
50+
</li>
51+
");
52+
}
53+
menubuilder.Append("</ul>\n");
54+
55+
string menuhtml = $@"
56+
<div class=""container"">
57+
<nav class=""navbar navbar-expand-lg navbar-dark mainbackground"">
58+
<a class=""navbar-brand"" href=""/"">XTLAB</a>
59+
<button class=""navbar-toggler"" type=""button""
60+
data-toggle=""collapse"" data-target=""#my-nav-bar""
61+
aria-controls=""my-nav-bar"" aria-expanded=""false"" aria-label=""Toggle navigation"">
62+
<span class=""navbar-toggler-icon""></span>
63+
</button>
64+
<div class=""collapse navbar-collapse"" id=""my-nav-bar"">
65+
{menubuilder}
66+
</div>
67+
</nav></div>";
68+
69+
return menuhtml;
70+
}
71+
72+
/// <summary>
73+
/// Những menu item mặc định cho trang
74+
/// </summary>
75+
/// <returns>Mảng các menuitem</returns>
76+
public static object[] DefaultMenuTopItems() {
77+
return new object[] {
78+
new {
79+
url = "/RequestInfo",
80+
label = "Request"
81+
},
82+
new {
83+
url = "/Product",
84+
label = "Product"
85+
}
86+
,
87+
new {
88+
url = "/Encoding",
89+
label = "Encoding"
90+
},
91+
new {
92+
url = "/Cookies",
93+
label = "Cookies"
94+
},
95+
new {
96+
url = "/Json",
97+
label = "JSON"
98+
}
99+
};
100+
}
101+
102+
public static string HtmlTrangchu() {
103+
return $@"
104+
<div class=""container"">
105+
<div class=""jumbotron"">
106+
<h1 class=""display-4"">Đây là một trang Web .NET Core</h1>
107+
<p class=""lead"">Trang Web này xây dựng trên nền tảng <code>.NET Core</code>,
108+
chưa sử dụng kỹ thuật MVC - nhằm mục đích học tập.
109+
Mã nguồn trang này tại <a target=""_blank""
110+
href=""https://github.com/xuanthulabnet/learn-cs-netcore/blob/master/ASP_NET_CORE/03.RequestResponse/"">
111+
Mã nguồn Ví dụ</a>
112+
113+
</p>
114+
<hr class=""my-4"">
115+
<p><code>.NET Core</code> là một hệ thống chạy đa nền tảng (Windows, Linux, macOS)</p>
116+
<a class=""btn btn-danger btn-lg"" href=""https://xuanthulab.net/lap-trinh-c-co-ban/"" role=""button"">Xem thêm</a>
117+
</div>
118+
</div>
119+
";
120+
121+
}
122+
123+
// Mở rộng String, phát sinh thẻ HTML với nội dụng là String
124+
// Ví dụ:
125+
// "content".HtmlTag() => <p>content</p>
126+
// "content".HtmlTag("div", "text-danger") => <div class="text-danger">content</div>
127+
public static string HtmlTag(this string content, string tag = "p", string _class = null) {
128+
string cls = (_class != null) ? $" class=\"{_class}\"":null;
129+
return $"<{tag + cls}>{content}</{tag}>";
130+
}
131+
public static string td(this string content, string _class = null) {
132+
return content.HtmlTag("td", _class);
133+
}
134+
public static string tr(this string content, string _class = null) {
135+
return content.HtmlTag("tr", _class);
136+
}
137+
public static string table(this string content, string _class = null) {
138+
return content.HtmlTag("table", _class);
139+
}
140+
141+
142+
}

ASP_NET_CORE/05.Session/Program.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Hosting;
6+
using Microsoft.Extensions.Configuration;
7+
using Microsoft.Extensions.Hosting;
8+
using Microsoft.Extensions.Logging;
9+
10+
namespace _05.Session
11+
{
12+
public class Program
13+
{
14+
public static void Main(string[] args)
15+
{
16+
CreateHostBuilder(args).Build().Run();
17+
}
18+
19+
public static IHostBuilder CreateHostBuilder(string[] args) =>
20+
Host.CreateDefaultBuilder(args)
21+
.ConfigureWebHostDefaults(webBuilder =>
22+
{
23+
webBuilder.UseStartup<Startup>();
24+
});
25+
}
26+
}

0 commit comments

Comments
 (0)