如何获取控制器中所有操作的当前用户
本文关键字:操作 用户 何获取 获取 控制器 | 更新日期: 2023-09-27 18:11:05
这是一个由两部分组成的
问题1(真题(
我有一个未绑定到模型的DashboardController
。必须先登录User
,然后才能访问仪表板。如何在执行每个操作之前运行检查以查看用户是否已通过身份验证,如果没有,则将其重定向到登录视图?我认为OnActionExecuted
是我想要的,但我不确定确切的实现应该是什么。我在这里走对了吗?
public class DashboardController : Controller
{
private ApplicationContext db = new ApplicationContext();
//
// GET: /Admin/
public ActionResult Index()
{
var categories = db.Categories.ToList();
return View(categories);
}
public ActionResult Product(int id)
{
var product = db.Products.Find(id);
return View(product);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if(Session["current_user"] == null)
{
// This (obviously) doesn't work - what should go here?
return RedirectToAction("Create", "Session");
}
base.OnActionExecuted(filterContext);
}
}
问题2
如果用户已登录,正确的方式是什么,可以在所有这些视图中访问用户?有人告诉我ViewBag
通常是个坏主意——我应该用什么?
我可以通过以下链接授权控制器和操作:它最初是用巴西葡萄牙语写的,但下面的链接被翻译成了英语。
https://translate.google.com.br/translate?sl=pt&tl=en&js=y&prev=_t&hl=pt BR&ie=UTF-8&u=http%3A%2F%2Fdevbrasil.net%2Fprofiles%2Blogs%2Fautentica-o-e-permiss-de-usu-rios-em-asp-net-mvc-4&编辑文本=&act=url
您可以通过让登录用户进入视图
@HttpContext.Current.User.Identity.Name
PS:对不起,我的英语不好
使用[Authorize]
atrribute。例如:
[AcceptVerbs(HttpVerbs.Get)]
[Authorize]
public ActionResult add()
{
}
然后在web.config 中
<authentication mode="Forms">
<forms name="my_cookie_name" loginUrl="~/login" defaultUrl="~/" timeout="2880"/>
</authentication>
如果用户未通过身份验证,它将自动重定向到登录页面。
如果你想要一些简单的东西来控制你的用户的身份,请在这里查看评分最高的答案:ASP.NET MVC-设置自定义IIdentity或IPrincipal。这是一个很好的例子。我在所有的项目中都使用类似的东西。
在我的登录操作中:
var user = _userService.system_login(systemlogin_model_post.email, systemlogin_model_post.password); // my user model
//... doing all sorts of validations
// once everyone is happy I create a cookie
Response.Cookies.Add(UserCookie.GetCookie(user));
比使用上面链接中的代码我创建cookie:
public static class UserCookie
{
public static HttpCookie GetCookie(User user)
{
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel { user_id = user.UserId, username = user.Username, roles = user.Roles ,session_token = GUIDGenerator.ToAlphaNumerical() };
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
user.UserId.ToString(),
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
return new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
}
}
当[Authorize]
被激发时,这个代码会处理它:
Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.user_id = serializeModel.user_id;
newUser.username = serializeModel.username;
newUser.roles = serializeModel.roles;
newUser.form_token = serializeModel.form_token;
HttpContext.Current.User = newUser;
}
}
1(ASP.NET MVC的Authorize属性完全集中在您的第一个问题上。您甚至可以进行自定义,但在大多数情况下不建议进行自定义。
2( 要分配当前登录的用户并在所有视图中可见,可以使用ViewBag/ViewModel属性将用户名绑定到Layout(_Layout.cs.html(,使其显示在使用布局的每个页面的顶部。
注意:如果要执行任何操作前调用逻辑,则在输入该操作方法之前,OnActionExecuting筛选器是正确的位置。
准确地说,您必须创建一个类,并且该类继承Controller类。
public class MyAuthentication : Controller
{
public MyAuthentication()
{
isAuthenticated();
}
private void isAuthenticated()
{
// do your authentication
//if user authenticated keep user details within a cookie, so that
// when the next request, program logic will search for cookie,
//if it is found then assume user was authenticated else redirect to login page.
}
}
然后在您的项目中为所有控制器继承这个MyAuthentication类
public class DashboardController : MyAuthentication
{
public ActionResult Index()
{
var categories = db.Categories.ToList();
return View(categories);
}
// rest of the codes
}
以便身份验证保持在单一位置。你可以在任何你想要的地方继承它。
如果您在控制器/操作中的任何位置都需要当前用户,那么更好的方法是在执行授权时设置用户数据。
在您的授权过滤器中,您可以使用
System.Web.HttpContext.Current.Items["userdata"]=userDataObject;
对于身份验证,本文可以提供帮助。
http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html
用户登录时首先放入表单验证Cookie。如
[HttpPost]
public ActionResult Login(Acccount obj){
// check whether the user login is valid or not
if(UseIsValid){
FormsAuthentication.SetAuthCookie(obj.username, obj.RememberMe);
return redirectToAction("Index","DashBoard");
}
return View(obj);
}
*和使用[授权]属性。像*
[Authorize]
public class DashboardController : Controller
{
private ApplicationContext db = new ApplicationContext();
public ActionResult Index()
{
var categories = db.Categories.ToList();
return View(categories);
}
}