正在将角色添加到现有项目中



我对向现有项目添加角色感到困惑,我将"身份验证"设置为";无认证";。我在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");
}
}

}
}

有多种方法可以实现这一点。

  1. 1.您可以创建一个通用主体,它接受两个参数身份和角色。Authorize属性查看主体附加到HttpContext以授权请求。https://www.sharpencode.com/article/MVC/filters-in-asp-net-mvc/authorize
2. You can create a Custom Role provider, which is the easiest. 

MVC 中的角色提供者

3. You can override Authorize Attribute

最新更新