User.Identity.Name始终返回我的Windows用户名

时间:2015-01-14 17:41:55

标签: c# asp.net-mvc-4 authentication login

我正在处理现有的应用程序。我们正在使用ASP.NET MVC 4。 当我启动身份验证模式是Windows但我想将其更改为表单身份验证。我为数据库中的身份验证用户创建了帐户控制器和登录操作。我做了以下

首先,我在web.config文件中将身份验证模式配置为表单。

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" cookieless="UseUri"/>
</authentication>**

其次,我在IIS服务器上启用表单身份验证

第三,我通过以下代码修改了Global.ASP

void Application_PostAuthenticateRequest()
    {
        if (User.Identity.IsAuthenticated)
        {

            Entities db = new Entities();

            var name = User.Identity.Name;
            var key = "Roles." + name;
            var roles = HttpContext.Current.Cache[key] as string[];
            if (roles == null)
            {

                //roles = db.GetRoles(HttpContext.Current.User.ToString()).ToArray();
                roles = db.GetRoles(name).ToArray();
                //HttpContext.Current.Cache.Remove(key);
                HttpContext.Current.Cache.Insert(key, roles, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);

            }
            HttpContext.Current.User =
                Thread.CurrentPrincipal =
                    new GenericPrincipal(User.Identity, roles);

        }

我的控制器和动作看起来像这样

[Authorize]

// [InitializeSimpleMembership]
    public class AccountController:Controller     {         实体db = new Entities();         用户users = new Users();         //         // GET:/帐户/         [使用AllowAnonymous]        public ActionResult Login()         {             return View(用户);         }

    // This Action is used to validate weather user is existing or not in a database
    [HttpPost]
    public ActionResult Login(Users user)
    {



        //Check Validation
        if (ModelState.IsValid)
        {
            //In this Action we are doing Form Authentication
            //Check the entred username and passwords are proper or not
            int? flag = db.GET_USER(user.UserName, user.Password).FirstOrDefault();

            if (flag == 1)
            {
                //use Form Authentication class to set cookie
                FormsAuthentication.SetAuthCookie(Request.Form["txtUserName"], true);
                //@Session["username"] = user.FirstName;
                return View("~/Views/Home/Index.cshtml");
            }
            else
            {
                ViewBag.ErrorMessage = "The user name or password you entered is incorrect.";
                return View("~/Views/Account/Login.cshtml");
            }
        }
        else
        {
            return View("~/Views/Account/Login.cshtml");
        }

    }

但仍然“User.Identity.Name”属性返回我的用户名而不是经过身份验证的用户的用户名。 我有什么想念吗?

谢谢你inadvance

0 个答案:

没有答案