一:MVC 中的攔截器
眾所周知,MVC 存在如下幾個主要的攔截器:IActionFilter、IExceptionFilter、IResultFilter、IAuthorizationFilter,
但是我們並不用這些攔截器,因為:
我們的業務邏輯面向多個平台,即有 Winform,有 Web Mvc 控制器,還有 Ios 等手機終端,在這些前台調用我們的服務的時候,我們不想為每個平台或者框架,使用它們各自的攔截器。
即便我們的平台只使用 Mvc ,我們也不使用這些攔截器,因為
1:基於 Attribute 的攔截器不能接受運行時參數。在MVC 的攔截器中可以得到 Http 上下文,如果你的參數藏在 Http Header 或者 Content 中,你也許會說,我們可以很容易的在攔截器內部獲取到這些參數。但是,誰說參數一定來自於 Http 中。
2:基於 Attribute 的攔截器只能在方法開始和結束的時候注入代碼。這有時候是個優點,
所有,我們需要一個通用的攔截器。
二:通用攔截器
public JsonResult TestJson()
{
return FrontProtector.Do1<JsonResult>(()=>
{
JsonResult re = new JsonResult();
return re;
});
}public ActionResult TestAction()
{
return null;
}public int TestInt(){
return FrontProtector.Do2<int>(()=>
{
return 0;
});
}class FrontProtector
{
public static T Do1<T>(Func<T> func) where T: class
{
T t = default(T);
try
{
// 1: 記錄日志;
// 2: 登錄判斷;
// 3: 如果有必要的話, 權限欺騙;
t = func();
return t;
}
catch
{
// 3: 包裝異常;
if( t is JsonResult)
{
return new JsonResult() as T;
}
return new {} as T;
}
}
public static T Do2<T>(Func<T> func) where T: struct
{
T t = default(T);
try
{
t = func();
return t;
}
catch
{
return default(T);
}
}
}