大佬教程收集整理的这篇文章主要介绍了asp.net-mvc – ASP.Net MVC 4通用主要困难,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当用户登录到我的网站时,我会执行以下操作
帐号控制器
public ActionResult Login(LoginModel model,String returnUrl) { if (ModelState.IsValid) { User user = _userservice.GetUser(model.Email.Trim()); //Create Pipe Delimited String to store UserID and Role(s) var userData = user.ApplicantID.ToString(); foreach (var role in user.UserRoles) { userData = userData + "|" + role.description; } _formAuthservice.SignIn(user.ApplicantFName,false,userData); return RedirectToAction("Index","Portfolio"); } return View(model); }
FormsAuthenticationservice
public class FormsAuthenticationservice : IFormsAuthenticationservice { public void SignIn(String userName,bool createPersistentCookie,String UserData) { if (String.IsNullOrEmpty(userName)) throw new Argumentexception("Value cAnnot be null or empty.","userName"); // Create and tuck away the cookie FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,userName,datetiR_851_11845@e.Now,datetiR_851_11845@e.Now.AddDays(15),createPersistentCookie,UserData); // Encrypt the ticket. String encTicket = FormsAuthentication.Encrypt(authTicket); //// Create the cookie. httpCookie faCookie = new httpCookie(FormsAuthentication.FormsCookiename,encTicket); httpContext.Current.Response.Cookies.Add(faCookiE); } }
Global.asax中
protected void Application_Authenticaterequest(Object sender,EventArgs E) { // Get the authentication cookie String cookiename = FormsAuthentication.FormsCookiename; httpCookie authCookie = Context.request.Cookies[cookiename]; // If the cookie can't be found,don't issue the ticket if (authCookie == null) return; // Get the authentication ticket and rebuild the principal // & identity FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.value); String[] UserData = authTicket.UserData.Split(new Char[] { '|' }); GenericIdentity userIdentity = new GenericIdentity(authTicket.Name); GenericPrincipal userPrincipal = new GenericPrincipal(userIdentity,UserData); Context.User = userPrincipal; }
此代码在我以前的MVC 3应用程序中运行良好,但在MVC 4应用程序中,在Razor View中,以下代码似乎没有访问IsInRole属性来执行角色检查
@if (httpContext.Current.User.IsInRole("Applicant")) { <p>text</text> }
再次,这在我的MVC 3应用程序中完美地工作。
有没有人有任何想法或建议,为什么这不会与我的MVC 4应用程序?
任何帮助深表感谢。
谢谢。
额外信息
我的MVC 4应用程序正在使用.Net Framework 4.0
下面的截图显示了我的General Principal,它被分配给Context.User。您可以看到,对于该用户,m_roles包含两个字符串,即UserID(100170)及其角色(申请人)。但是由于某种原因,IsInRoles不能在我的MVC 4 Razor View中访问或看到,但是它可以在我的MVC 3 Razor View中。
以上是大佬教程为你收集整理的asp.net-mvc – ASP.Net MVC 4通用主要困难全部内容,希望文章能够帮你解决asp.net-mvc – ASP.Net MVC 4通用主要困难所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。