目前在公司新開發了一個項目,第一次正式使用.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 狀態碼,以達到跳轉到錯誤頁的目的。
