“”采用了前后端代码分离的架构,即“miidy.cloud.console”站与“miidy.cloud.manage”站(两个前端站)同时通过web api的方式调用“miidy.cloud.restweb” web服务,以达到前后端代码分离的方式(详情请查看麦荻网教系统的)。因为“miidy.cloud.manage”站只开放给具备管理权限的用户,故除了在前端增加控制外,还需在“miidy.cloud.restweb” web服务内进行权限控制。那么,如何在“miidy.cloud.restweb” web服务内根据用户实现权限控制呢?

 

iactionfilter

在“miidy.cloud.restweb”程序内,我们将借助iactionfilter接口来实现请求的拦截。该接口提供了两个方法()分别为:onactionexecuted(action执行后)、onactionexecuting(action执行前)。根据需求,我们实现onactionexecuting即可。

 

attribute

我们再借助“attribute”属性特性,可帮助我们在“miidy.cloud.restweb”指定的方法内按需使用拦截器,这样便可很方便的达到权限控制的目的。

 

实现

如上面所述,我们已经清楚了整个实现思路,那么下面就来看看“miidy.cloud.restweb”程序拦截器的代码实现吧:

1、首先我们先创建一个名为“manageverifyattribute”的拦截器类,命名以“attribute”结尾,并继承“attribute”类,与实现“iactionfilter”。并在onactionexecuting方法内写入业务代码。具体代码如下:

  1 
  2 namespace miidy.cloud.provider
  3 {
  4     /// <summary>
  5     /// 该过虑器提供给所有对外的restapi接口使用
  6     /// 在有需要验证每个接口/方法是否只为管理人员用户调用时使用
  7     /// 方法级别的过率器
  8     /// </summary>
  9     public class manageverifyattribute : attribute, iactionfilter
 10     {
 11         public void onactionexecuted(actionexecutedcontext context)
 12         {
 13         }
 14 
 15         /// <summary>
 16         /// 判断用户是否为管理角色,不是则抛出异常
 17         /// </summary>
 18         /// <param name="context"></param>
 19         public void onactionexecuting(actionexecutingcontext context)
 20         {
 21             if (context.httpcontext.user.identity.isauthenticated)
 22             {
 23                 var roletype = int.parse(context.httpcontext.user.claims.first(c => c.type == "roletype").value);
 24                 //不是管理人员
 25                 if (roletype <= 0 || roletype >= 4)
 26                 {
 27                     context.result = new jsonresult(new result(214));
 28                 }
 29             }
 30             else
 31                 context.result = new jsonresult(new result(214));
 32         }
 33 
 34     }
 35 }
 36 

 

2、在web api的方法内打上[manageverify]属性,即可完成拦截器的功能实现了,具体如下:

  1 
  2 /// <summary>
  3 /// 同步单个数据,数据不存在则增加,否则修改
  4 /// </summary>
  5 /// <param name="ids"></param>
  6 /// <returns></returns>
  7 [route("synchrdatabymodel")]
  8 [httppost]
  9 [manageverify]
 10 public async task<result> synchrdatabymodel(mc_ware model)
 11 {
 12     var resul = await _warecore.synchrdataasync(new list<mc_ware> { model });
 13     if (resul <= 0)
 14         return new result(211);
 15     return new result(200);
 16 }

 

 

总结

1、基于“iactionfilter”接口来实现请求的拦截。

2、基于“attribute”属性特性可帮助我们可以按需在指定webapi方法内使用拦截器。

 

声明

本文为作者原创,转载请备注出处与保留原文地址,谢谢。如文章能给您带来帮助,请点下推荐或关注,感谢您的支持!