【发布时间】:2021-07-01 20:49:31
【问题描述】:
我对向现有项目添加角色感到困惑,我将身份验证设置为“无身份验证”。 我在 mssql 中有数据库,字段只有“用户名”和“密码”。我用它来进行身份验证。我的问题是我如何为授权添加“管理员”或“用户A”或“访客”等角色。我对 Mvc 很陌生。谢谢!
这是我的控制器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace _3131.Controllers {
public class HomeController : Controller {
[Authorize]
public ActionResult Index(string button) {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "admin") {
return View();
}else if(viewdata == "userA") {
return View();
} else if(viewdata == "userB") {
return View();
} else {
return View();
}
}
[Authorize]
public ActionResult About() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "admin") {
return View();
}else {
return View("Error");
}
}
[Authorize]
public ActionResult UserA() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if(viewdata == "userA" || viewdata == "admin") {
return View();
}else {
return View("Error");
}
}
[Authorize]
public ActionResult UserB() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if (viewdata == "userB" || viewdata == "admin") {
return View();
} else {
return View("Error");
}
}
[Authorize]
public ActionResult UserC() {
ViewData["username"] = User.Identity.Name;
var viewdata = Convert.ToString(ViewData["username"]);
if (viewdata == "userC" || viewdata == "admin") {
return View();
} else {
return View("Error");
}
}
}
}
【问题讨论】: