1. 程式人生 > >針對Linux ASP.NET MVC網站中 httpHandlers配置無效的解決方案

針對Linux ASP.NET MVC網站中 httpHandlers配置無效的解決方案

近期有Linux ASP.NET使用者反映,在MVC網站的Web.config中新增 httpHandlers 配置用於處理自定義型別,但是在執行中並沒有產生預期的效果,伺服器返回了404(找不到網頁)錯誤。經我親自測試,在WebForm網站中,httpHandlers節點的配置是有效的,而在MVC中的確無效。如果這個問題不能解決,將嚴重影響Linux ASP.NET的部署,也影響WIN ASP.NET向Linux遷移的相容性和完整性。

造成httpHandlers無效的原因我並沒有時間去深究,為了能夠及時解決這個問題,我把注意力放到了Global.asax檔案的Application_BeginRequest方法上,然後給出如下的解決方案。

一,在global.asax中新增一個靜態方法:

static bool TryHanler<T>(string ext) where T : IHttpHandler
{
    if (string.IsNullOrEmpty(ext)) return false;
    var context = HttpContext.Current;
    var path = context.Request.AppRelativeCurrentExecutionFilePath;
    if (!path.EndsWith(ext)) return false;
    var handle = Activator.CreateInstance(typeof(T)) as IHttpHandler;
    if (handle == null) return false;
    handle.ProcessRequest(context);
    context.Response.End();
    return true;
}

說明:這是一個泛型方法,T代表你用於處理某個路徑的繼承自IHttpHandler的自定義類,引數ext是這個處理類所處理的請求路徑的副檔名(含“.”號)。

二,在global.asax中實現Application_BeginRequest方法,並在該方法中呼叫TryHandler。如:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if(TryHandler<myHandler>(".do")) return;
}

注:該處理方案具有通用性,能同時相容 Windows IIS和 Linux Jexus或XSP。