2009-06-11 44 views
2

我正在使用ASP.NET MVC作为项目。我使用了很多用户控制,我需要检查当前用户并检查它是否具有角色等,现在我在每个UserControl中创建用户,我看到权限。我想改变它,所以我只创建一次。获取asp.net MVC中的当前用户,以便我可以检查用户控件中的操作

问题是Whta是最好的aproch? viewData [“用户”] =用户和获取用户窗体在这里或什么?你建议什么,所以我可以摆脱这条线

LCP.eTorneos.Dal.EntityFramework.JugadorRepository jugadorRepository = 
        new LCP.eTorneos.Dal.EntityFramework.JugadorRepository(); 
var jugador = jugadorRepository.GetJugador(User.Identity.Name) 
<% if (Page.User.Identity.IsAuthenticated && jugador.IsAdmin) { %> 
     ... 
<%}%> 

回答

1

我相信是这样的:

<%= Utils.GetJugador(ViewData).IsAdmin %> 

比这更好:

<%= Html.GetJugador().IsAdmin %> 

因为的HtmlHelper扩展仅用于生成HTML标记

UPDATE:

using System.Web.Mvc; 
using LCP.eTorneos.Dal.EntityFramework; 

public static class Utils { 
    public static Jugador GetJugador(ViewDataDictionary ViewData) { 
     return ViewData["JugadorActual"] as Jugador; 
     /* OR maybe ? 
     * return (Jugador)(ViewData["JugadorActual"] ?? new Jugador()); 
     */ 
    } 
} 

希望这有助于

3

有2个选项。首先,使用ViewData [“用户”] - 最简单但不是最好的(不是强类型)。第二个(如果你使用的视图模型),使用基础视角模型的所有视图模型:

public class BaseViewModel { 
    public Jugador Jugador; 

    // Or simply add flag 

    public IsAdmin; 
} 

public class ConcreteViewModel : BaseViewModel { 
    public YourModel Model; 
} 

在控制器:

var model = new ConcreteViewModel { 
    Model = yourModel, 
    IsAdmin = true /* false */ 
}; 

return View(model); 

在浏览:

<%@ Page MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ConcreteViewModel>" %> 

<!-- Or in SiteMaster: --> 

<%@ Master Inherits="System.Web.Mvc.ViewMasterPage<BaseViewModel>" %> 

<% if(Model.IsAdmin) { %> 

... 

<% } %> 

更新:

最好避免重复你的代码和使用自定义过滤器设置ViewModel的基本部分:

public class IsAdminAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     // ... 

     (filterContext.Controller.ViewData.Model as BaseViewModel).IsAdmin = true; /* flase */ 
    } 
} 
+0

这工作,但你真的不得不让这个角色在每个控制器中都设置好。一旦没有完成,该值将从请求中获取。它很高兴在一个过滤器。 – 2009-06-12 09:56:35

+0

好点,我会更新我的答案 – 2009-06-12 10:31:00

1

首先感谢@ eu-ge-ne。

这我我做什么,我愿意接受新的建议,但这似乎工作: 我创建了一个ActionFilterAttribute这样的:

public class JugadorAttribute : ActionFilterAttribute { 
    public override void OnActionExecuted(ActionExecutedContext filterContext) { 
     JugadorRepository jugadorRepository = new JugadorRepository(); 
     Jugador jug = jugadorRepository.GetJugador(filterContext.HttpContext.User.Identity.Name); 
     filterContext.Controller.ViewData["JugadorActual"] = jug; 
    } 
} 

这让在ViewData的页当前播放器。然后在我的控制器我这样做:

[JugadorAttribute()] 
public class HomeController : Controller { 

现在的问题是这ViewData的能力不强类型化的,所以我在HTML类创建这个帮手:

public static class JugadorHelper { 
    public static Jugador GetJugador(this HtmlHelper html) { 
     return ((LCP.eTorneos.Dal.EntityFramework.Jugador)html.ViewData["JugadorActual"]); 
    } 
} 

而且Whoala,现在我可以做到这一点在我的观点:

Html.GetJugador().IsAdmin 
相关问题