using System;
using System.Web;
using System.Web.UI;
namespace AspxBoy.VisualUrl
{
///
/// VisualUrlHttpHander 的摘要说明。
///
public class VisualUrlHttpHander : IHttpHandlerFactory
{
#region IHttpHandlerFactory 成员
public void ReleaseHandler(IHttpHandler handler)
{
// TODO: 添加 VisualUrlHttpHander.ReleaseHandler 实现
}
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
// TODO: 添加 VisualUrlHttpHander.GetHandler 实现
string rawUrl = context.Request.RawUrl.Trim();
///
///这里只示范地址是http://domainname/xxx
///和http://domainname/xxx/这样的地址
///
string userName = rawUrl.TrimStart('/').TrimEnd('/');
string sendToUrl = url;
string filePath = pathTranslated;
string sendToUrlLessQString;
sendToUrl = Globals.AppPath + "/get.aspx?username=" + userName;
globals.rewriteurl(context, sendToUrl, out sendToUrlLessQString, out filePath);
return PageParser.GetCompiledPageInstance(sendToUrlLessQString, filePath, context);
}
#endregion
}
public class Globals
{
///
/// 应用程序路径
///
public static string AppPath
{
get
{
string applicationPath = "/";
if(HttpContext.Current != null)
{
applicationPath = HttpContext.Current.Request.ApplicationPath;
}
if (applicationPath == "/")
{
return string.Empty;
}
else
{
if (applicationPath.EndsWith("/"))
{
return applicationPath;
}
else
{
return applicationPath + "/";
}
}
}
}
///
/// 在ASP.NET中执行URL重写
/// see http://www.aspxboy.com/484/archive.aspx
///
///
///
///
///
public static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
{
if (context.Request.QueryString.Count > 0)
{
if (sendToUrl.IndexOf('?') != -1)
{
sendToUrl += "&" + context.Request.QueryString.ToString();
}
else
{
sendToUrl += "?" + context.Request.QueryString.ToString();
}
}
string queryString = String.Empty;
sendToUrlLessQString = sendToUrl;
if (sendToUrl.IndexOf('?') > 0)
{
sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
}
filepath = string.Empty;
filePath = context.Server.MapPath(sendToUrlLessQString);
context.rewritepath(sendtourllessqstring, String.Empty, queryString);
}
}
}