激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - C# - 基于mvc5+ef6+Bootstrap框架實(shí)現(xiàn)身份驗(yàn)證和權(quán)限管理

基于mvc5+ef6+Bootstrap框架實(shí)現(xiàn)身份驗(yàn)證和權(quán)限管理

2021-11-29 14:42豐叔叔 C#

最近剛做完一個(gè)項(xiàng)目,項(xiàng)目架構(gòu)師使用mvc5+ef6+Bootstrap,用的是vs2015,數(shù)據(jù)庫(kù)是sql server2014。下面小編把mvc5+ef6+Bootstrap項(xiàng)目心得之身份驗(yàn)證和權(quán)限管理模塊的實(shí)現(xiàn)思路分享給大家,需要的朋友可以參考下

近和朋友完成了一個(gè)大單子架構(gòu)是ef="/article/51254.html">mvc5+ef6+Bootstrap,用的是vs2015,數(shù)據(jù)庫(kù)是sql server2014。朋友做的架構(gòu),項(xiàng)目完成后覺(jué)得很多值得我學(xué)習(xí),在這里總結(jié)下一些心得。

創(chuàng)建項(xiàng)目一開始刪掉App_Start目錄下的IdentityConfig.cs和Startup.Auth.cs文件;清空Modle文件夾,Controller文件夾和相應(yīng)的View; 刪除目錄下的ApplicationInsights.config文件和Startup.cs文件

修改web.config文件(添加<add key="owin:AutomaticAppStartup" value="false"/>不使用Startup.cs文件來(lái)啟動(dòng)項(xiàng)目)

?
1
2
3
4
5
6
7
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="owin:AutomaticAppStartup" value="false"/> <!--去掉創(chuàng)建項(xiàng)目初的Startup.cs文件的設(shè)置-->
</appSettings>

(不用他們是因?yàn)樽詭У倪@些內(nèi)容太冗余)

去掉冗余內(nèi)容正式開始,首先介紹數(shù)據(jù)庫(kù)這一塊,數(shù)據(jù)庫(kù)我們是配置的可以手動(dòng)生成和修改的

1.在項(xiàng)目目錄想創(chuàng)建Migrations文件夾,里面添加Configuration.cs文件

?
1
2
3
4
5
6
7
8
9
10
11
12
internal sealed class Configuration : DbMigrationsConfiguration<AccountContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "UserProject.DAL.AccountContext";
}
protected override void Seed(AccountContext context)
{
//base.Seed(context);
}
}

在Modle文件夾下添加AccountContext.cs文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class AccountContext:DbContext
{
public AccountContext():base("AccountContext") {
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
<connectionStrings>
<add name="AccountContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UserProject.mdf;Initial Catalog=UserProject;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

然后 使用vs2015里面的工具-NuGet包管理器-程序包管理控制平臺(tái)

輸入add-migration Initial 按回車,在輸入update-database按回車。在App_Data文件夾下就會(huì)看到AccountContext數(shù)據(jù)庫(kù)了。

2.在Modle文件夾下添加User.css文件

?
1
2
3
4
5
6
7
8
9
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Role Role { get; set; }
}
public enum Role//角色枚舉
{ 管理員 = 0, 員工 = 1, 經(jīng)理 = 2, 總經(jīng)理 = 3, 董事長(zhǎng) = 4 }

在ViewModle文件夾中添加Account.cs文件

?
1
2
3
4
5
6
7
8
public class Account
{
[Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public string RePassword { get; set; }
}

這里推薦創(chuàng)建BaseController之后的Controller就繼承它來(lái)使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class BaseController : Controller
{
public string UserName => User.Identity.Name;
public AccountContext db = new AccountContext();
private User _userInfo = null;
public User CurrentUserInfo
{
get
{
if (_userInfo == null)
{
var user = db.Users.SingleOrDefault(u => u.UserName == UserName);//此處為了不每次訪問(wèn)用戶表可以做一個(gè)靜態(tài)類,里面存放用戶表信息.
_userInfo = user == null ? null : new User()
{
ID = user.ID,
UserName = user.UserName,
Role = user.Role
};
}
return _userInfo;
}
}
    //驗(yàn)證角色:獲取Action的CustomAttributes,過(guò)濾角色
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var authRoleAtt = filterContext.ActionDescriptor.GetCustomAttributes(false).SingleOrDefault(att => att is AuthorizeRoleAttribute) as AuthorizeRoleAttribute;
if (authRoleAtt == null && CurrentUserInfo != null)
return;
if (!authRoleAtt.Roles.Contains(CurrentUserInfo.Role))
{
filterContext.Result = View("NoPermission", "_Layout", "您沒(méi)有權(quán)限訪問(wèn)此功能!");
}
}
//這里是記log用
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var msg = $"用戶: {CurrentUserInfo?.UserName}, 鏈接: {Request.Url}";
if (Request.HttpMethod == "POST")
msg += $", 數(shù)據(jù): {HttpUtility.UrlDecode(Request.Form.ToString())}";
//Log.Debug(msg);
}
}

AdminController繼承BaseController

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Authorize]
public ActionResult Index()
{
return View(db.Users.ToList());
}
[Authorize, AuthorizeRole(Role.管理員)]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}

登錄頁(yè)面:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@model UserProject.ViewModels.Account
@{
ViewBag.Title = "Login";
}
@using (Html.BeginForm("Login", "Admin",FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
@Html.AntiForgeryToken()
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="登錄" class="btn btn-primary" />
</div>
</div>
}

登錄的Action:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost, AllowAnonymous]
public ActionResult Login(Account model)
{
if (ModelState.IsValid)
{
var user = db.Users.SingleOrDefault(t => t.UserName == model.Name && t.Password == model.Password);
if (user != null)
{
FormsAuthentication.SetAuthCookie(model.Name, false);//將用戶名放入Cookie中
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("Name", "用戶名不存在!");
}
}
return View(model);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}

按照以上方式 訪問(wèn)Details這個(gè)Action的時(shí)候必須是管理員角色。

以上所述是小編給大家介紹的基于mvc5+ef6+Bootstrap框架實(shí)現(xiàn)身份驗(yàn)證和權(quán)限管理,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!

原文鏈接:http://www.cnblogs.com/shootingstar/p/5629668.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 妇女毛片| 蜜桃91丨九色丨蝌蚪91桃色 | 美女网站黄在线观看 | 天天色综合2 | 欧美在线小视频 | 国产妇女乱码一区二区三区 | 亚洲第五色综合网 | 久久人体 | 欧美一级黄色免费看 | 噜噜噜在线 | 成年人网站国产 | 久久久久久免费 | 精品亚洲午夜久久久久91 | 中文在线观看视频 | 中文亚洲视频 | 久久免费激情视频 | 朋友不在家 | 一级黄色在线观看 | 成人午夜免费福利 | 爽成人777777婷婷 | 91久久精品一区二区 | 天天碰天天操 | 成人免费一区二区三区在线观看 | 色成人在线 | 国产午夜探花 | 国产三级在线观看a | 国产亚洲美女精品久久久2020 | 亚洲视频高清 | 3344永久免费 | 国产美女自拍av | 欧美成人三级大全 | 久久av喷吹av高潮av懂色 | 视频久久免费 | 中文字幕国产亚洲 | 美女在线视频一区二区 | 色网站综合| 看个毛片 | 中文字幕在线亚洲精品 | 国产一国产一级毛片视频在线 | 色屁屁xxxxⅹ在线视频 | 成年免费在线视频 |