近期有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。