Asp.net-Mvc

ASP.Net MVC 4 通用主要困難

  • February 11, 2013

我正在開發一個ASP.Net MVC 4 Web 應用程序。以前我的 MVC 應用程序是使用MVC 3開發的,而對於這個新的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, DateTime.Now, DateTime.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);
   }
}

全球.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 視圖中,以下程式碼似乎沒有訪問IsInRole屬性來執行角色檢查

@if (HttpContext.Current.User.IsInRole("Applicant"))
{
   <p>text</text>
}

同樣,這在我的 MVC 3 應用程序中執行良好。

有人對為什麼這不適用於我的 MVC 4 應用程序有任何想法或建議嗎?

任何幫助深表感謝。

謝謝。

額外的資訊

我的 MVC 4 應用程序正在使用 .Net Framework 4.0

下面的螢幕截圖顯示了分配給Context.User的我的****通用主體。您可以看到對於這個使用者,m_roles包含兩個字元串,使用者 ID (100170) 和他們的角色(申請人)。但是由於某種原因,在我的MVC 4 Razor 視圖中無法訪問或看到IsInRoles,但是,它可以在我相同的MVC 3 Razor 視圖中訪問或查看。 在此處輸入圖像描述

鄉親

我終於解決了這個問題。創建新的 ASP.NET MVC 4 應用程序時,預設情況下會啟用SimpleMembershipProvider 。在這種情況下,我不想使用SimpleMembershipProvider,但是,我需要在我的 web 配置中使用以下行禁用它

<appSettings>
   <add key="enableSimpleMembership" value="false" />
</appSettings>

我對User.IsInRole的呼叫現在效果很好。

希望這對其他人有幫助。

在 MVC 4 中,您可以訪問Userfrom WebPageRenderingBase,因此在 razor 語法中,您可以直接訪問User實例:

@if (Request.IsAuthenticated && User.IsInRole("Applicant"))
{
   <p>text</p>
}

我看到您正在手動創建一個FormsAuthenticationTicket和一個。HttpCookieFormsAuthentication 類將使用SetAuthCookie(string, bool[, string]). 從這個意義上說,您的身份驗證服務可以簡化為:

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");

       FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
   }
}

事實證明,您還需要更改Application_AuthenticateRequestApplication_OnPostAuthenticateRequest

protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)

引用自:https://stackoverflow.com/questions/14772034