如何:在RIA Services中允许角色功能
 使用角色,我们可以指定哪个验证用户组可以访问某些资源。WCF RIA Services中的角色功能是建立在ASP.NET的角色功能上的。
 我们只有在用户已经被验证后,才能检索用户的角色信息。通过在域操作中的方法上使用RequireRoleAttribute属性,我们就可以限制角色中的成员对域操作的访问。
 
 配置服务端项目
 1. 在服务端项目中,打开Web.config文件。
 2. 在段中,添加元素。
  
| 
        1 
        
        2 
        
        3 
        
        4 
        
        5 
        
        6 
        | <SYSTEM.WEB>  <AUTHENTICATIONmode="Forms"></AUTHENTICATION>  <ROLEMANAGERenabled="true"></ROLEMANAGER></SYSTEM.WEB> | 
 3. 在成员数据库中,创建所需的角色并赋予用户所需的角色。更多详情,可看后面的章节。
 4. 要确保只有指定角色中的成员才能访问域操作,我们需要对域操作应用RequireRoleAttribute属性。
  
| 
        1 
        
        2 
        
        3 
        
        4 
        
        5 
        
        6 
        
        7 
        | [RequiresRole("Managers")]publicIQueryable<CUSTOMER> GetCustomers(){
               returnthis.ObjectContext.Customers;} | 
 
 在客户端使用角色
 1. 要检测是否用户属于要求的角色,使用Roles属性或调用WebContext.Current.User对象的IsInRole方法。下面示例了在调用域操作之前,检测是否用户属于Managers的角色。
  
| 
        1 
        
        2 
        
        3 
        
        4 
        
        5 
        
        6 
        
        7 
        
        8 
        
        9 
        
        10 
        
        11 
        
        12 
        
        13 
        
        14 
        
        15 
        
        16 
        
        17 
        
        18 
        
        19 
        | privatevoidLoadRestrictedReports(){
               LoadOperation<SALESORDERHEADER> loadSales = context.Load(context.GetSalesOrderHeadersQuery().Take(numberOfRows));    SalesOrdersGrid.ItemsSource = loadSales.Entities;    SalesOrdersGrid.Visibility = System.Windows.Visibility.Visible;    if(WebContext.Current.User.IsInRole("Managers"))    {
                   LoadOperation<CUSTOMER> loadCustomers = context.Load(context.GetCustomersQuery().Take(numberOfRows));        CustomersGrid.ItemsSource = loadCustomers.Entities;        CustomersGrid.Visibility = System.Windows.Visibility.Visible;    }    else    {
                   CustomersGrid.Visibility = System.Windows.Visibility.Collapsed;    }} | 
 2. 如果想让WebContext对象在XAML中可用,那么在创建RootVisual之前,在Application.Startup事件中把当前WebContext实例添加到应用程序资源中。
  
| 
        1 
        
        2 
        
        3 
        
        4 
        
        5 
        
        6 
        
        7 
        | privatevoidApplication_Startup(objectsender, StartupEventArgs e){
               this.Resources.Add("WebContext", WebContext.Current);    this.RootVisual = new MainPage();} |