ASP.NET友好URL

23
6个回答

29

这个示例使用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, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </httpModules>
</system.web>
<system.webServer><modules><add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers
…   
        <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler,                 System.Web, Version=2.0.0.0, Culture=neutral,              PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>
</system.webServer>

第二步 - 在global.asax中添加路由表

定义从友好的URL到aspx页面的映射,保存请求的用户ID以备后用。

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")
    ));
}

第三步 - 实现路由处理程序

在路由处理之前,将查询字符串添加到当前上下文中。

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的代码

这是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;
}

我知道这是一个老问题,但在谷歌上得分很高。为什么GetHttpHandler从未被调用?我在其中放置了生成运行时错误的代码,确实所有方法都被调用了,除了请求中的GetHttpHandler。 - HMR

8
这是一个使用ASP.NET Routing实现友好URL的替代示例。
该应用程序处理的映射示例包括: http://samplesite/userid/1234 - http://samplesite/users.aspx?userid=1234 http://samplesite/userid/1235 - http://samplesite/users.aspx?userid=1235 此示例不使用查询字符串,但在aspx页面上需要额外的代码
第一步-将必要的条目添加到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, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </httpModules>
</system.web>
<system.webServer><modules><add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers
…   
        <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler,                 System.Web, Version=2.0.0.0, Culture=neutral,              PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>
</system.webServer>

步骤2 - 在global.asax中添加路由表

定义从友好的URL到aspx页面的映射,并保存请求的用户ID以供后续使用。

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")
    ));
}

步骤三 - 实现路由处理程序

将包含参数的路由上下文传递给页面。(请注意IRoutablePage的定义)

using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Web.Routing;

public interface IRoutablePage
{
    RequestContext RequestContext { set; }
}

public class CustomRouteHandler : IRouteHandler
{
    public CustomRouteHandler(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; private set; }

    public IHttpHandler GetHttpHandler(RequestContext
          requestContext)
    {
        var page = BuildManager.CreateInstanceFromVirtualPath
             (VirtualPath, typeof(Page)) as IHttpHandler;

        if (page != null)
        {
            var routablePage = page as IRoutablePage;

            if (routablePage != null) routablePage.RequestContext = requestContext;
        }

        return page;
    }
}

步骤4 - 在目标页面检索参数

请注意IRoutablePage的实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Routing;

public partial class users : System.Web.UI.Page, IRoutablePage
{
    protected RequestContext requestContext;

    protected object RouteValue(string key)
    {
        return requestContext.RouteData.Values[key];
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string id = RouteValue("userid").ToString();
        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;
        }
    }

    #region IRoutablePage Members

    public RequestContext RequestContext
    {
        set { requestContext = value; }
    }

    #endregion
}

我在这个实现方案上比另一个方案运气更好。当使用Ajax时,queryString存在问题。这个实现方案有点复杂,但是付出的努力是值得的。 - proudgeekdad

1

以下是使用ASP.NET MVC进行操作的另一种方式

首先,这是带有两个动作的控制器代码。Index从模型获取用户列表,userid获取单个用户:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcApplication1.Controllers
{
    public class UsersController : Controller
    {
        public ActionResult Index()
        {
            return View(Models.UserDB.GetUsers());
        }
        public ActionResult userid(int id)
        {
            return View(Models.UserDB.GetUser(id));
        }
    }
}

这是Index.asp视图,它使用ActionLink以正确的格式创建链接:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Index" %>
<%@ Import Namespace="MvcApplication1.Controllers" %>
<%@ Import Namespace="MvcApplication1.Models" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <div>
    <h2>Index of Users</h2>
           <ul>
            <% foreach (User user in (IEnumerable)ViewData.Model) { %>
                 <li>
                       <%= Html.ActionLink(user.name, "userid", new {id = user.id })%>
                 </li>
            <% } %>
           </ul>
    </div>
</body>
</html>

这里是userid.aspx视图,显示个人详细信息:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="userid.aspx.cs" Inherits="MvcApplication1.Views.Users.userid" %>
<%@ Import Namespace="MvcApplication1.Controllers" %>
<%@ Import Namespace="MvcApplication1.Models" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>
        <table border ="1">
            <tr>
                <td>
                ID
                </td>
                <td>
                <%=((User)ViewData.Model).id %>
                </td>
            </tr>
            <tr>
                <td>
                Name
                </td>
                <td>
                <%=((User)ViewData.Model).name %>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

最后为了完整起见,这是模型代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class UserDB
    {
        private static List<User> users = new List<User>{
            new User(){id=12345, name="Bill"},
            new User(){id=12346, name="Claire"},
            new User(){id=12347, name="David"}
        };

        public static List<User> GetUsers()
        {
            return users;
        }

        public static User GetUser(int id)
        {
            return users.First(user => user.id == id);
        }

    }

    public class User
    {
        public int id { get; set; }
        public string name { get; set; }
    }
}

1

我一直在使用Intelligencia的URL重写器:

http://urlrewriter.net/

配置非常简单 - 可能只需要一个小时就可以全部设置好并运行。几乎没有什么问题...

我会推荐它,但是我应该提到我没有尝试过其他的。

祝你好运!


0

我已经为这个问题开发了一个开源的NuGet库,它会隐式地将EveryMvc/Url转换为every-mvc/url。

破折号连接的URL更加友好且易于阅读。小写URL往往会创建较少的问题。(更多请参见我的博客文章

NuGet包:https://www.nuget.org/packages/LowercaseDashedRoute/

要安装它,只需通过右键单击项目并选择NuGet包管理器,在“在线”选项卡中输入“Lowercase Dashed Route”,然后它应该弹出。

或者,您可以在“程序包管理器控制台”中运行此代码

Install-Package LowercaseDashedRoute

之后,您应该打开App_Start/RouteConfig.cs文件,注释掉现有的route.MapRoute(...)调用,并添加以下内容:

routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);

就是这样。所有的URL都是小写、带破折号,并且在不需要你做任何其他操作的情况下隐式转换。

开源项目链接:https://github.com/AtaS/lowercase-dashed-route


0
此外,还可以查看ASP.NET MVC或如果你喜欢Web Forms,则可以查看ASP.NET 3.5 SP1中的新System.Web.Routing命名空间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接