设置HttpContext.Current.UserHttpContext、Current、User

由网友(酷似你妈)分享简介:我开发一个asp.net的MVC 3.0应用程序,它有一个简单的身份验证过程。用户填写由AJAX调用发送到服务器,并获得响应的一种形式,但这里的问题是,使用下面的方法:FormsAuthentication.SetAuthCookie(person.LoginName,假);不足以填满'HttpContext.Curr...

我开发一个asp.net的MVC 3.0应用程序,它有一个简单的身份验证过程。用户填写由AJAX调用发送到服务器,并获得响应的一种形式,但这里的问题是,使用下面的方法:

  FormsAuthentication.SetAuthCookie(person.LoginName,假);
 

不足以填满'HttpContext.Current.User'和它需要的以下方法来运行:

  FormsAuthentication.RedirectFromLoginPage(...);
 

这里的问题是,正如我所说,在loggin形式使用ajax的形式,并获得和JSON响应,所以重定向是不可能的。

我怎么能填补HttpContext.Current.User?

感谢。

更新:

关于 HttpContext.Current.User.Identity.Name 的问题

下面是注册方法:

  [HttpPost]
        公众的ActionResult注册(人人)
        {
            变种Q = da.Persons.Where(X => x.LoginName == person.LoginName.ToLower())。FirstOrDefault();

            如果(Q!= NULL)
            {
                ModelState.AddModelError(,用户名是repettive,尝试另一个人);

                返回JSON(新对象[] {假,this.RenderPartialViewToString(RegisterControl,人)});
            }
            其他
            {
                如果(person.LoginName.ToLower()==管理员)
                {
                    person.IsAdmin = TRUE;
                    person.IsActive = TRUE;
                }

                da.Persons.Add(人);

                da.SaveChanges();

                FormsAuthentication.SetAuthCookie(person.LoginName,假);
返回JSON(新对象[] {真,您已成功注册!});

}

}
 

解决方案

下面是我最终使用的版本,这是由@ AdamTuliper-MSFT基于答案。它只是意味着要在登录后立即使用,但重定向之前,允许其他code访问 HttpContext.User中

如果已经通过身份验证不要做任何 在不修改cookie的,因为这应该只用于此请求的寿命 在缩短一些事情,和一个小更安全用户数据(不应该是空的,但...)

调用此调用SetAuthCookie(后),如下图所示:

  //在登录功能
FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
AuthenticateThisRequest();

私人无效AuthenticateThisRequest()
{
    //注意:如果已经登录的用户的(如根据不同的用户帐户)
    //那么这将不会复位身份信息。请注意这一点,如果
    //你让业已登录的用户重新登录作为不同账户
    //无需先注销。
    如果(HttpContext.User.Identity.IsAuthenticated)回报;

    VAR名称= FormsAuthentication.FormsCookieName;
    VAR饼干= Response.Cookies [名]
    如果(饼干!= NULL)
    {
        VAR票= FormsAuthentication.Decrypt(cookie.Value);
        如果(门票= NULL和放大器;!&安培;!ticket.Expired)
        {
            字符串[]角色=(ticket.UserData为字符串 - ).Split('');
            HttpContext.User中=新的GenericPrincipal(新FormsIdentity(门票),角色);
        }
    }
}
 

编辑:删除调用Request.Cookies时,如@ AdamTuplier-MSFT提到的

I am developing an asp.net mvc 3.0 application which has a simple authentication process. User fills a form which is sent to server by ajax call and gets response, but the problem here is that using the following method :

FormsAuthentication.SetAuthCookie(person.LoginName,false);

is not enough to fill 'HttpContext.Current.User' and it needs the below method to be run :

FormsAuthentication.RedirectFromLoginPage("...");

Problem here is that as i mentioned, the loggin form uses an ajax form, and get responses with json, so redirecting is not possible.

How could I fill 'HttpContext.Current.User' ?

Thanks.

Update :

Here is register method :

 [HttpPost]
        public ActionResult Register(Person person)
        {
            var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault();

            if (q != null)
            {
                ModelState.AddModelError("", "Username is repettive, try other one");

                return Json(new object[] { false, this.RenderPartialViewToString("RegisterControl", person) });
            }
            else
            {
                if (person.LoginName.ToLower() == "admin")
                {
                    person.IsAdmin = true;
                    person.IsActive = true;
                }

                da.Persons.Add(person);

                da.SaveChanges();

                FormsAuthentication.SetAuthCookie(person.LoginName,false);
return Json(new object[] { true, "You have registered successfully!" });

}

}

解决方案

Here is the version I ended up using, which is based on the answer by @AdamTuliper-MSFT. It is only meant to be used right after logging in, but before redirect, to allow other code to access HttpContext.User.

Don't do anything if already authenticated Doesn't modify the cookie, since this should only be used for the lifetime of this request Shorten some things, and a little safer with userdata (should never be null, but...)

Call this after you call SetAuthCookie(), like below:

// in login function
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
AuthenticateThisRequest();

private void AuthenticateThisRequest()
{
    //NOTE:  if the user is already logged in (e.g. under a different user account)
    //       then this will NOT reset the identity information.  Be aware of this if
    //       you allow already-logged in users to "re-login" as different accounts 
    //       without first logging out.
    if (HttpContext.User.Identity.IsAuthenticated) return;

    var name = FormsAuthentication.FormsCookieName;
    var cookie = Response.Cookies[name]; 
    if (cookie != null)
    {   
        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        if (ticket != null && !ticket.Expired)
        {
            string[] roles = (ticket.UserData as string ?? "").Split(',');
            HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), roles);
        }
    }
}

Edit: Remove call to Request.Cookies, as @AdamTuplier-MSFT mentioned.

阅读全文

相关推荐

最新文章