Python框架总是提供方法来处理以优雅的方式传达请求数据的URL,例如
http://somewhere.overtherainbow.com/userid/123424/
我想让你注意到结束路径/ userid / 123424 /
你如何在ASP.NET中这样做?
解决方法
此示例使用ASP.NET路由来实现友好的URL。
应用程序处理的映射示例如下:
http://samplesite/userid/1234 – http://samplesite/users.aspx?userid=1234
http://samplesite/userid/1235 – http://samplesite/users.aspx?userid=1235
此示例使用查询字符串,并避免任何修改aspx页面上的代码的要求。
步骤1 – 将必要的条目添加到web.config
<system.web> <compilation debug="true"> <assemblies> … <add assembly="System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation> … <httpModules> … <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,System.Web.Routing,PublicKeyToken=31BF3856AD364E35" /> </httpModules> </system.web> <system.webServer> … <modules> … <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers … <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler,System.Web,Version=2.0.0.0,PublicKeyToken=b03f5f7f11d50a3a"/> </handlers> </system.webServer>
步骤2 – 在global.asax中添加路由表
定义从友好的URL到aspx页面的映射,保存请求的用户名以供以后使用。
void Application_Start(object sender,EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("UseridRoute",new Route ( "userid/{userid}",new CustomRouteHandler("~/users.aspx") )); }
步骤3 – 实现路由处理程序
在发生路由之前,将querystring添加到当前上下文中。
using System.Web.Compilation; using System.Web.UI; using System.Web; using System.Web.Routing; public class CustomRouteHandler : IRouteHandler { public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { // Add the querystring to the URL in the current context string queryString = "?userid=" + requestContext.RouteData.Values["userid"]; HttpContext.Current.RewritePath( string.Concat( VirtualPath,queryString)); var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath,typeof(Page)) as IHttpHandler; return page; } }
来自users.aspx的代码
protected void Page_Load(object sender,EventArgs e) { string id = Page.Request.QueryString["userid"]; switch (id) { case "1234": lblUserId.Text = id; lblUserName.Text = "Bill"; break; case "1235": lblUserId.Text = id; lblUserName.Text = "Claire"; break; case "1236": lblUserId.Text = id; lblUserName.Text = "David"; break; default: lblUserId.Text = "0000"; lblUserName.Text = "Unknown"; break; }