Skip to content

Commit

Permalink
建立角色
Browse files Browse the repository at this point in the history
  • Loading branch information
malagege committed Aug 19, 2022
1 parent b36f5e0 commit 578bdd6
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
55 changes: 55 additions & 0 deletions AuthSample/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using AuthSample.ViewModels.Admin;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace AuthSample.Controllers
{
[Authorize]
public class AdminController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;

public AdminController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public IActionResult Index()
{
return View();
}

[HttpGet]
public IActionResult CreateRole()
{
return View();
}

[HttpPost]
public async Task<IActionResult> CreateRoleAsync(CreateRoleViewModel model)
{
if (ModelState.IsValid)
{
//角色 Name 不能重覆
var identityRole = new IdentityRole
{
Name = model.RoleName,
};

IdentityResult result = await _roleManager.CreateAsync(identityRole);

if (result.Succeeded)
{
return RedirectToAction("index", "home");
}

foreach(IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
return View(model);
}
}
}
11 changes: 11 additions & 0 deletions AuthSample/ViewModels/Admin/CreateRoleViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;

namespace AuthSample.ViewModels.Admin
{
public class CreateRoleViewModel
{
[Required]
[Display(Name = "角色")]
public string RoleName { get; set; }
}
}
18 changes: 18 additions & 0 deletions AuthSample/Views/Admin/CreateRole.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@using AuthSample.ViewModels.Admin
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewBag.Title = "建立角色";
}
@model CreateRoleViewModel
<form asp-action="CreateRole" method="post">
<div>
<label asp-for="RoleName"></label>
<input asp-for="RoleName" />
<span asp-validation-for="RoleName"></span>
</div>
<div>
<button>創建角色</button>
</div>
</form>
3 changes: 3 additions & 0 deletions AuthSample/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,7 @@ else
<a asp-controller="account" asp-action="login">登入</a>
</div>
}
<div>
<a asp-controller="admin" asp-action="createrole">建立角色</a>
</div>
Index

0 comments on commit 578bdd6

Please sign in to comment.