需求:
在Aps.Net 應用中,對於瀏覽器請求的部分url的地址自定義處理,不交給路由系統或頁面。
解決方案:
在全局文件Global.asax中 ,提供Application_BeginRequest 事件,這個事件可以監聽到,本網站的所有請求都會經過這。此處根據url自定義輸出響應內容,並結束響應就可以了。
自定義攔截請求示例1:
1.Global.asax 中代碼處理
public class MvcApplication : System.Web.HttpApplication { LogHelper.LogHelper _log = new LogHelper.LogHelper(); protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } /// <summary> /// 接收請求 /// </summary> protected void Application_BeginRequest() { _log.WriteLine("請求地址:" + Request.Url.AbsoluteUri); //攔截請求 string[] segments = Request.Url.Segments; if (segments.Length > 1 && segments[1].ToLower() == "testone") { //需要自己指定輸出內容和類型 Response.ContentType = "text/html;charset=utf-8"; Response.Write("請求攔截處理"); Response.End(); // 此處結束響應,就不會走路由系統 } } }
2.不攔截的默認Action 定義
public class TestOneController : Controller { // GET: TestOne public ActionResult Index() { return Content("測試首頁"); } }
注:調試說明,如果指定Response.End() ,就不會走路由系統,執行Action。
自定義擴展模塊攔截請求處理示例2
1.定義模塊,繼承IHttpModule

/// <summary> /// 定時任務常用邏輯封裝 /// 注:每天指定小時內循環觸發,原因,保證這個小時中程序在運行或有一次訪問,定時任務可以執行 /// </summary> public class TimedTask:IHttpModule { /// <summary> /// 需要全局對象,保證多線程參數統一 /// </summary> public static TaskParams Params = new TaskParams(); /// <summary> /// 標記已經運行 /// </summary> public void SetRuned() { Params.Hour_State = true; } /// <summary> /// 任務對象 /// </summary> private static Task _Task = null; /// <summary> /// 執行事件處理 /// </summary> public Action OnRunning = null; /// <summary> /// 執行異常 /// </summary> public Action<Exception> OnError = null; /// <summary> /// 監聽請求處理 /// </summary> private void Init() { } /// <summary> /// 開啟監聽處理 /// </summary> public void Start() { if (_Task != null) { //if (_Task.Status != TaskStatus.Running) //{ // _Task.RunSynchronously(); //} return; } //開啟定時任務 _Task = new Task(() => { while (true) { try { //判斷達到對應小時執行 if (DateTime.Now.Hour == Params.TaskHour) { //外部處理,具體內容 OnRunning?.Invoke(); } else { Params.Hour_State = false; } } catch (Exception ex) { Params.error_state = 1; Params.error_msg = ex.Message; OnError?.Invoke(ex); } //等待處理 Thread.Sleep(Params.SleepSpan); } }); _Task.Start(); } public void Init(HttpApplication app) { //請求監聽處理 app.BeginRequest += (object sender, EventArgs e) => { HttpResponse resp = app.Response; HttpRequest req = app.Request; if (req.HttpMethod == "GET") { //攔截請求 string[] segments = req.Url.Segments; if (segments.Length > 1 && segments[1].ToLower() == "gettaskinfo") { if (_Task == null) throw new Exception("當前定時任務對象沒有初始化"); JObject obj = JObject.FromObject(_Task); //合並參數 obj.Merge(JObject.FromObject(Params)); resp.Write(obj.ToString()); resp.ContentType = "application/json;charset=utf-8"; resp.End(); } } }; } public void Dispose() { throw new NotImplementedException(); } } /// <summary> /// 定時任務的參數定義 /// </summary> public class TaskParams { /// <summary> /// 定時任務每天運行的時間點 /// </summary> public int TaskHour { get; set; } = 3; /// <summary> /// 間隔執行的時間段,單位/毫秒,默認6分鍾一次執行 /// </summary> public int SleepSpan { get; set; } = 1000 * 60 * 6; /// <summary> /// 判斷當前小時是否已經執行,每次執行完任務標記為true /// </summary> public bool Hour_State { get; set; } /// <summary> /// 判斷異常狀態 /// </summary> public int error_state; /// <summary> /// 異常消息內容 /// </summary> public string error_msg; }
2.注冊啟動模塊
在AssemblyInfo程序加載文件定義:
//定義程序啟動時處理方法 [assembly: PreApplicationStartMethod(typeof(TestOne), "Start")]
在啟動方法中,注冊模塊和啟用定時任務,關於啟動方法:http://www.cnblogs.com/tianma3798/p/8251858.html
public class TestOne { /// <summary> /// 程序啟動時,PreApplicationStartMethod中指定的方法必須是公共靜態的 /// </summary> public static void Start() { LogHelper.LogHelper _log = new LogHelper.LogHelper(); _log.WriteLine("程序啟動成功1"); //啟用定時任務 TimedTask _task = new TimedTask(); //指定運行的小時點 TimedTask.Params.TaskHour = DateTime.Now.Hour; TimedTask.Params.SleepSpan = 1000 * 5; _task.OnRunning += () => { _task.SetRuned(); _log.WriteLine("定時任務已經執行"); }; _task.OnError += (ex) => { _log.WriteLine("定時任務執行失敗:" + ex.Message); }; _task.Start(); HttpApplication.RegisterModule(typeof(TimedTask)); } }
更多:
Asp.Net HttpApplication請求管道與Session(一)
Asp.Net HttpApplication請求管道與Session(二)