.NET MVC4 ApiController拦截器的使用


目前在公司新开发了一个项目,第一次正式使用.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 状态码,以达到跳转到错误页的目的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM