Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取控制器中所有操作的当前用户?_C#_Asp.net_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 如何获取控制器中所有操作的当前用户?

C# 如何获取控制器中所有操作的当前用户?,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,这是一个由两部分组成的项目 问题1(真正的问题) 我有一个未绑定到模型的仪表板控制器。用户必须先登录才能访问仪表板。在执行每个操作之前,如何运行检查以查看用户是否经过身份验证,如果没有,如何将其重定向到登录视图?我想,OnActionExecuted是我想要的,但我不确定具体的实现应该是什么。我走对了吗 public class DashboardController : Controller { private ApplicationContext db = new Applicati

这是一个由两部分组成的项目

问题1(真正的问题) 我有一个未绑定到模型的
仪表板控制器
用户必须先登录才能访问仪表板。在执行每个操作之前,如何运行检查以查看用户是否经过身份验证,如果没有,如何将其重定向到登录视图?我想,
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
通常是个坏主意-我应该使用什么?

1)ASP.NET MVC的Authorize属性完全集中在您的第一个问题上。您甚至可以进行自定义,但大多数情况下不建议这样做

2) 要分配当前登录的用户并在所有视图中可见,可以使用ViewBag/ViewModel属性将用户名绑定到布局(_Layout.cshtml),以便它显示在使用布局的每个页面的顶部


注意:如果要执行任何预操作调用逻辑,则在进入该操作方法之前,OnActionExecuting筛选器是正确的位置。

我可以通过以下链接授权控制器和操作: 最初是巴西葡萄牙语,但下面的链接被翻译成英语

您可以通过以下方式获取登录用户的视图:

@HttpContext.Current.User.Identity.Name

PS:对不起,我的英语不好

确切地说,您必须创建一个类,该类继承控制器类

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;
对于身份验证,本文可以提供帮助


使用
[授权]
属性。 例如:

    [AcceptVerbs(HttpVerbs.Get)]
    [Authorize]
    public ActionResult add()
    {

    }
然后在web.config中

<authentication mode="Forms">
  <forms name="my_cookie_name" loginUrl="~/login" defaultUrl="~/" timeout="2880"/>
</authentication>
而不是使用上面链接中的代码创建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;
            }
        }
受保护的无效应用程序\u PostAuthenticateRequest(对象发送方,事件参数e)
{
HttpCookie authCookie=Request.Cookies[FormsAuthentication.formscookeName];
if(authCookie!=null)
{
FormsAuthenticationTicket authTicket=FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer=新的JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel=serializer.Deserialize(authTicket.UserData);
CustomPrincipal newUser=newcustomprincipal(authTicket.Name);
newUser.user\u id=serializeModel.user\u id;
newUser.username=serializeModel.username;
newUser.roles=serializeModel.roles;
newUser.form_token=serializeModel.form_token;
HttpContext.Current.User=newUser;
}
}

当用户登录时,首先放入表单身份验证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]属性。像*

[Authorize]
public class DashboardController : Controller
{
    private ApplicationContext db = new ApplicationContext();

    public ActionResult Index()
    {
        var categories = db.Categories.ToList();
        return View(categories);
    }
}

尝试Authorize属性。我不知道你的第二个问题是什么意思,viewbag和它有什么关系?自定义操作筛选器。事实上,你应该在HTTP管道中更早地进行身份验证和授权。我的常规方法是一个HTTP模块,它使用上下文身份验证并使用IIdentity和IPrincipal接口授权事件。这样,未经授权的用户可以在任何页面加载发生之前被适当重定向,并且应用程序在应用程序中任何位置都可以访问的每个请求上都有当前已验证的用户凭据。@CodeCaster如果用户经过身份验证,我想让该用户可以从视图中访问。是否有一种方法可以将用户(存储在会话中)分配给视图中的每个操作都可以访问的值,这样我就可以执行如下操作:
Hello@user.FirstName@user.LastName
@NickZimmerman我当然愿意这样做,您是否有文章或其他内容的链接?(或者你能把答案贴在详细的地方吗?)。但是我在
isAuthenticated()
方法中触发了一个异常。我的逻辑是
if(Session[“current\u user”]==null)//do redirect
,但异常表示
Session[“current\u user”]
未设置为对象的实例。如何确定范围/规避该问题?像下面这样使用System.Web.HttpContext.Current.Session[“Current_user”]而不是Session[“Current_user”]如何设置Authorize属性以使用现有的用户模型?
[Authorize]
public class DashboardController : Controller
{
    private ApplicationContext db = new ApplicationContext();

    public ActionResult Index()
    {
        var categories = db.Categories.ToList();
        return View(categories);
    }
}