博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.NET MVC4 ApiController拦截器的使用

Posted on 2013-10-18 15:27  无名小站  阅读(8746)  评论(1编辑  收藏  举报

目前在公司新开发了一个项目,第一次正式使用.NET MVC4来搭建,用拦截器来处理权限验证。

自定义拦截器需继承ActionFilterAttribute类,重写OnActionExecuting和OnActionExecuted方法来实现在控制器调用之前或之后切入,不过继承此类只可在Controller中使用,而非ApiController。

如果想自定义ApiController拦截器,需继承System.Web.Http.Filters.ActionFilterAttribute(类名虽一样,但命名空间不同)

 1     public class ApiPermissionFilter : ActionFilterAttribute
 2     {
 3         #region 属性
 4 
 5         /// <summary>
 6         /// 数据权限编码
 7         /// </summary>
 8         public string Code
 9         { get; set; }
10 
11         #endregion
12 
13         public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
14         {
15             UserInfo service = new UserInfo();
16 
17             try
18             {
19                 if (!service.IsInPermission(Code))
20                 {
21                     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
22                 }
23             }
24             catch (Exception ex)
25             {
26                 SmartCardCommon.LogHelper.WriteErrorLog(ex.Message, ex);
27                 throw ex;
28             }
29             finally
30             {
31                 SmartCardCommon.NhibernaterSessionHelper.CloseSession();
32             }
33         }
34     }

这样,同样可以用标记特性的方式来使用Api拦截器。

在拦截器中跳转页面,不可使用Response.Redirect方式,这样会遇到意外的错误。可以直接设置HTTP 状态码,以达到跳转到错误页的目的。