我這樣做是爲了授權用戶。如何使用ASP.NET MVC 4中的數據庫用戶列表來授權控制器操作中的用戶?
[Authorize(Users = @"user1, user2, user3")]
public class MyController : Controller
{
// my stuff
}
我想從用戶這是在數據庫表中的列表做授權..
我這樣做是爲了授權用戶。如何使用ASP.NET MVC 4中的數據庫用戶列表來授權控制器操作中的用戶?
[Authorize(Users = @"user1, user2, user3")]
public class MyController : Controller
{
// my stuff
}
我想從用戶這是在數據庫表中的列表做授權..
此鏈接形式Gotalove是有幫助的。 嘗試以下操作:
「使用和@VikasRana http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF
共享的鏈接我擺脫了我的枚舉角色的我的方法
public CustomAuthorizeAttribute(params object[] roles)
{ ...}
然後我改變角色在我的模型是一個字符串如:User.Role =「管理」,而不是INT在我onAuthorization方法我把它改爲:
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Controller.TempData["ErrorDetails"] = "You don't have access rights to this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
}
,在我的Global.asax加入這個
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true && Request.IsAuthenticated== true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
using (GManagerDBEntities db = new GManagerDBEntities())
{
User user = db.Users.SingleOrDefault(u => u.Username == username);
roles = user.Role;
}
//let us extract the roles from our own custom cookie
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//something went wrong
}
}
}
}
「
來源:Custom user authorization based with roles in asp.net mvc
PS:在此環節,在同一職位,有解決您的問題第二種方式。 在帖子的底部。
如果這不能幫助你,你應該嘗試。
儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – emmanuel
好的,對不起。我將包括它 –
實施自定義授權過濾器聽起來像你可以做的最好的。 –