6

我有一个使用 VS 2012 Internet 应用程序(简单会员)构建的网站 EF Code First

更新

我想知道如何扩展HttpContext.User.IsInRole(role)自定义表的功能 -> User.IsInClient(client)

4

4 回答 4

15

这是我建议解决您的问题的方法:

创建您自己的实现接口System.Security.Principal,您可以在其中放置您需要的任何方法:

public interface ICustomPrincipal : IPrincipal
{
    bool IsInClient(string client);
}

实现这个接口:

public class CustomPrincipal : ICustomPrincipal
{
    private readonly IPrincipal _principal;

    public CustomPrincipal(IPrincipal principal) { _principal = principal; }

    public IIdentity Identity { get { return _principal.Identity; } }
    public bool IsInRole(string role) { return _principal.IsInRole(role); }

    public bool IsInClient(string client)
    {
        return _principal.Identity.IsAuthenticated 
               && GetClientsForUser(_principal.Identity.Name).Contains(client);
    }

    private IEnumerable<string> GetClientsForUser(string username)
    {
        using (var db = new YourContext())
        {
            var user = db.Users.SingleOrDefault(x => x.Name == username);
            return user != null 
                        ? user.Clients.Select(x => x.Name).ToArray() 
                        : new string[0];
        }
    }
}

Global.asax.cs中,将您的自定义主体分配给请求用户上下文(如果您打算稍后使用它,可以选择分配给执行线程)。我建议Application_PostAuthenticateRequest不要将此事件Application_AuthenticateRequest用于此分配,否则您的主体将被覆盖(至少被 ASP.NET MVC 4 覆盖):

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    Context.User = Thread.CurrentPrincipal = new CustomPrincipal(User);

    /* 
     * BTW: Here you could deserialize information you've stored earlier in the 
     * cookie of authenticated user. It would be helpful if you'd like to avoid 
     * redundant database queries, for some user-constant information, like roles 
     * or (in your case) user related clients. Just sample code:
     *  
     * var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
     * var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
     * var cookieData = serializer.Deserialize<CookieData>(authCookie.UserData);
     *
     * Next, pass some deserialized data to your principal:
     *
     * Context.User = new CustomPrincipal(User, cookieData.clients);
     *  
     * Obviously such data have to be available in the cookie. It should be stored
     * there after you've successfully authenticated, e.g. in your logon action:
     *
     * if (Membership.ValidateUser(user, password))
     * {
     *     var cookieData = new CookieData{...};         
     *     var userData = serializer.Serialize(cookieData);
     *
     *     var authTicket = new FormsAuthenticationTicket(
     *         1,
     *         email,
     *         DateTime.Now,
     *         DateTime.Now.AddMinutes(15),
     *         false,
     *         userData);
     *
     *     var authTicket = FormsAuthentication.Encrypt(authTicket);
     *     var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
                                           authTicket);
     *     Response.Cookies.Add(authCookie);
     *     return RedirectToAction("Index", "Home");
     * }
     */         
}

接下来,为了能够使用控制器中的属性UserHttpContext无需ICustomPrincipal每次都将其强制转换,请定义基本控制器,您可以在其中覆盖默认User属性:

public class BaseController : Controller
{
    protected virtual new ICustomPrincipal User
    {
        get { return (ICustomPrincipal)base.User; }
    }
}

现在,让其他控制器继承它:

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        var x = User.IsInClient(name); 

如果您使用Razor View Engine,并且您希望能够在视图上以非常相似的方式使用您的方法:

@User.IsInClient(name)

您需要重新定义WebViewPage类型:

public abstract class BaseViewPage : WebViewPage
{
    public virtual new ICustomPrincipal User
    {
        get { return (ICustomPrincipal)base.User; }
    }
}

public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual new ICustomPrincipal User
    {
        get { return (ICustomPrincipal)base.User; }
    }
}

并告诉 Razor 通过修改Views\Web.config文件的相应部分来反映您的更改:

<system.web.webPages.razor>
    ...
    <pages pageBaseType="YourNamespace.BaseViewPage">
于 2013-09-09T14:41:04.353 回答
0

使用 Linq:

var Users = Membership.GetAllUsers();

//**Kinda Like Users.InCLients(userName).
var users = from x in Users 
              join y in db.Clinets on x.ProviderUserKey equals y.UserID
              select x

//**Kinda Like Clients.InUsers(userName)
var clients = from x in db.Clinets
              join y in Users on x.UserID equals y.ProviderUserKey
              select x
于 2013-08-21T20:17:16.540 回答
-1

试试这个方法

List<Clinets> AllClinets =entityObject.Clinets .ToList();

Foreach( var check in AllClinets)
{
  if(check.UserTable.RoleTable.RoleName=="Rolename1")
   {
      //This users are Rolename1 
   }
  else
   {
   //other.
   }
}
于 2013-08-22T03:33:37.920 回答
-2

在这种情况下,存储过程会更好。

于 2013-09-04T05:42:42.983 回答