17

我正在开发一个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 视图中访问或查看。 在此处输入图像描述

4

3 回答 3

19

乡亲

我终于解决了这个问题。创建新的 ASP.NET MVC 4 应用程序时,默认情况下会启用SimpleMembershipProvider 。在这种情况下,我不想使用SimpleMembershipProvider,但是,我需要在我的 web 配置中使用以下行禁用它

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

我对User.IsInRole的调用现在效果很好。

希望这对其他人有帮助。

于 2013-02-11T11:16:10.200 回答
4

在 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)
于 2013-02-10T12:55:16.077 回答
1

在 MVC 4 HttpContext.Current.User中没有公开,所以你不能使用它。我所做的是创建一个自定义 BaseViewPage 并在其中添加以下代码。

    public abstract class BaseViewPage : WebViewPage
    {
        public virtual new Principal User
        {
            get { return base.User as Principal; }
        }
    }

    public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
    {
        public virtual new Principal User
        {
            get { return base.User as Principal; }
        }
    }

然后在 Views 文件夹中对system.web.webPages.razor/pages部分的web.config进行以下更改。

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="WebApp.Views.BaseViewPage">
  <namespaces>
    ...
  </namespaces>
</pages>

希望这能解决您的问题。

于 2013-02-10T20:23:06.413 回答