种形式来书写很不错,这就产生另一个“漫无边际”的想法,请看下面的写法:
this.Url<Foo>(new { param1 = "value1", param2 = "value2" });
当然,执行效率肯定稍逊一筹啦,因为用了反射(题外话,其实大家可以不必闻“射”丧胆,老赵的关于快速反射的开源项目很好很强大)。
public static string Url(this IHttpHandler httpHandler, object param) { string queryString = param.ToQueryString(); string virtualPath = string.Format("{0}?{1}", httpHandler.Url(), queryString); return virtualPath; }
/// 拼装查询字符串 public static string ToQueryString(this T model) { StringBuilder sb = new StringBuilder(); if (model != null) { Type type = model.GetType(); //遍历所有属性,拼装查询字符串 type.GetProperties().ForEach(p => { sb.Append(p.Name); sb.Append("="); sb.Append(UrlEncode(p.GetValue(model, null))); sb.Append("&"); }); if (sb.Length > 0) { //去掉最后一个“&” return sb.ToString(0, sb.Length - 1); } } return sb.ToString(); } /// Url编码 public static string UrlEncode(object obj) { if (obj == null) { return string.Empty; } else if (obj is DateTime) { string value = ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss.ffffff"); return System.Web.HttpUtility.UrlEncode(value); } return System.Web.HttpUtility.UrlEncode(obj.ToString()); }
以上代码关于 Url 编码的部分,你可以看到如果是DateTime类型转字符串时,这里进行特定格式的转化。因为如果不这样转化,当获取这个DateTime类型时,不能保证能从字符串转回正确的DateTime。
那么,有了上面介绍,自然而然一堆扩展方法就呼之欲出了:
public static void View(this IHttpHandler httpHandler) { HttpContext.Current.Response.Redirect(httpHandler.Url()); } public static void View(this IHttpHandler httpHandler, object param) { HttpContext.Current.Response.Redirect(httpHandler.Url(param)); } public static void ViewHome(this IHttpHandler httpHandler) { HttpContext.Current.Response.Redirect("~"); } public static void ViewLogin(this IHttpHandler httpHandler) { ViewLogin(httpHandler,null); } public static void ViewLogin(this IHttpHandler httpHandler, string returnUrl) { string virtualPath = FormsAuthentication.LoginUrl; if (!string.IsNullOrEmpty(returnUrl)) virtualPath += "?ReturnUrl=" + returnUrl; HttpContext.Current.Response.Redirect(virtualPath); }
结束
当然没结束。以上的 Url 返回的只能是.aspx的页面,那么IHttpHandl |