ASP.Net MVC 4 Generic Principal Difficulties

痴心易碎 提交于 2019-12-02 19:15:59

Folks

I finally resolved this issue. It appears by default the SimpleMembershipProvider is enabled when you create a new ASP.NET MVC 4 application. I did not want to use the SimpleMembershipProvider on this occasion, however, I needed to disable it in my web config with the following line

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

My call to User.IsInRole works great now.

Hope this helps someone else.

In MVC 4 you can access the User from the WebPageRenderingBase, so inside razor syntax you have direct access to the User instance:

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

I see that you are creating a FormsAuthenticationTicket and an HttpCookie manually. The FormsAuthentication class would do this for you using SetAuthCookie(string, bool[, string]). In this sense your auth service can be reduced to:

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

It turns out you also need to change Application_AuthenticateRequest to Application_OnPostAuthenticateRequest:

protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)

In MVC 4 HttpContext.Current.User is not exposed so you can't use it. What i did was create a custom BaseViewPage and added following code in it.

    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; }
        }
    }

And then make following changes to system.web.webPages.razor/pages section your web.config in Views folder.

<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>

Hope this solves your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!