ASP.NET AJAX Advance Tips & Tricks (7) ASP.NET AJAX 与 URLRewriting
前言:
最近一些使用URLRewriting的朋友们有时候会遇到ASP.NET AJAX和AJAX Control Toolkit控件不能正常工作的现象,对于没有相关经验的开发者来说相当棘手。本篇通过案例分析和相对的解决方案来讨论在使用ASP.NET AJAX 与 URLRewriting 时应当注意到的一些兼容性问题。
问题重现:
一般简单的URLRewriting应用都是对来自客户端对资源的Request进行路径重定向,比较典型的写法如同下列代码1 和代码2:
代码1:
// If the requested file exists
if (File.Exists(Request.PhysicalPath))
{
// Do nothing here, just serve the file
}
// If the file does not exist then
else if (!File.Exists(Request.PhysicalPath))
{
// Get the URL requested by the user
string sRequestedURL = Request.Path.Replace(".aspx", "").Replace("/gratis24/","");
// You can retrieve the ID of the content from database that is
// relevant to this requested URL (as per your business logic)
string sId;
sId = GetContentIDByPath(sRequestedURL);
// The ShowContents.aspx page should show contents relevant to
// the ID that is passed here
string sTargetURL = "~/Kategori.aspx?category=" + sId;
// Owing to RewritePath, the user will see requested URL in the
// address bar
// The second argument should be false, to keep your references
// to images, css files
Context.RewritePath(sTargetURL, false);
代码2:
void Application_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpContext httpContext = HttpContext.Current;
String currentURL = httpContext.Request.Path.ToLower();
//Creates the physical path on the server
string physicalPath = httpContext.Server.MapPath(currentURL.Substring(currentURL.LastIndexOf("/") + 1));
//checks to see if the file does not exsists.
if (!System.IO.File.Exists(physicalPath) && !currentURL.EndsWith("webresource.axd"))
{
string reWritePage = "ViewProfile.aspx";
httpContext.RewritePath(reWritePage);
}
}
然而,当我们使用上面的代码进行URLRewriting,并且在页面中使用ASP.NET AJAX 或 AJAX Control Toolkit的话,将会得到:'sys' is undefined 错误警告,而AJAX控件不能正常工作,totally not work.
分析:
很显然,'sys' is undefined 告诉我们 ASP.NET AJAX框架没有正常加载,根据分析可知,sys的定义是在脚本资源文件ScriptResource.axd中的,然而在上面的URLRewriting代码中,我们并没有对ScriptResource.axd进行特殊处理,导致该资源被重定向,没有正常加载。所以导致了ASP.NET AJAX不工作的问题。
解决方法:
知道了原因,我们就要修改URLRewriting的代码,为ScriptResource.axd增加一个例外:
代码1的解决方案:
在CheckPath时加入特例
{
if (!string.Equals(path, VirtualPathUtility.ToAbsolute("~/ScriptResource.axd"), StringComparison.OrdinalIgnoreCase))
//it should be at the root.
{
Throw404();
}
}
代码2的解决方案:
与1同理,在IO判断时加上特例,修改如下:
{
System.Web.HttpContext httpContext = HttpContext.Current;
String currentURL = httpContext.Request.Path.ToLower();
//Creates the physical path on the server
string physicalPath = httpContext.Server.MapPath(currentURL.Substring(currentURL.LastIndexOf("/") + 1));
//checks to see if the file does not exsists.
if (!System.IO.File.Exists(physicalPath) && !currentURL.EndsWith("webresource.axd") && !currentURL.EndsWith("ScriptResource.axd"))
{
string reWritePage = "ViewProfile.aspx";
httpContext.RewritePath(reWritePage);
}
}
至此,可解决该问题。
相关case:
http://forums.asp.net/t/1178119.aspx
http://forums.asp.net/p/1356089/2795441.aspx#2795441
Thanks.