你可以簡單地重寫接口,像這樣的東西
[HttpPost]
public ActionResult Login(MVVMLogin LoginData)
{
//validate user against database
var IsValid = true;
if (IsValid == true)
{
var Roles = "admin";
var authTicket = new FormsAuthenticationTicket(
1,
LoginData.Username,
DateTime.Now,
DateTime.Now.AddMinutes(20), //Expires
false,
Roles,
"/");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
}
return View();
}
,並在Global.asax你可以添加以下
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User == null) return;
if (!HttpContext.Current.User.Identity.IsAuthenticated) return;
if (!(HttpContext.Current.User.Identity is FormsIdentity)) return;
var id = HttpContext.Current.User.Identity as FormsIdentity;
var ticket = id.Ticket;
var userData = ticket.UserData;
var roles = userData.Split(new[] { ',' });
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
現在你可以控制哪些類型的用戶可以訪問控制器
[Authorize(Roles = "admin,user")]
public class CampaignsController : Controller
這正是我的想法! – NULL