Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ASP.NET的友好URL_Asp.net_Url_Rest_Friendly Url - Fatal编程技术网

ASP.NET的友好URL

ASP.NET的友好URL,asp.net,url,rest,friendly-url,Asp.net,Url,Rest,Friendly Url,Python框架总是提供处理URL的方法,这些URL以优雅的方式传递请求的数据,例如 我希望您注意到结束路径/userid/123424/ 如何在ASP.NET中实现这一点?此外,请查看ASP.NET MVC,或者如果您是在webforms上设置的,请查看ASP.NET 3.5 SP1中新的System.Web.Routing命名空间。此示例使用ASP.NET路由实现友好的URL 应用程序处理的映射示例有: - - 本例使用querystring,避免了在aspx页面上修改代码的任何要求 步骤1

Python框架总是提供处理URL的方法,这些URL以优雅的方式传递请求的数据,例如

我希望您注意到结束路径/userid/123424/


如何在ASP.NET中实现这一点?

此外,请查看ASP.NET MVC,或者如果您是在webforms上设置的,请查看ASP.NET 3.5 SP1中新的System.Web.Routing命名空间。此示例使用ASP.NET路由实现友好的URL

应用程序处理的映射示例有:

-
-

本例使用querystring,避免了在aspx页面上修改代码的任何要求

步骤1-将必要的条目添加到web.config 步骤3-实现路由处理程序 在路由发生之前,将查询字符串添加到当前上下文中

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

这是另一个使用ASP.NET路由实现友好URL的示例

应用程序处理的映射示例有:

-
-

此示例不使用查询字符串,但需要在aspx页面上添加代码

步骤1-将必要的条目添加到web.config 步骤3-实现路由处理程序 将包含参数的路由上下文传递给页面。(请注意IRoutablePage的定义)

步骤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
}
下面是使用ASP.NET MVC的另一种方法 首先,这里是带有两个操作的控制器代码。索引从模型中获取用户列表,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; }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
名称空间MVCAPApplication1.Models
{
公共类用户数据库
{
私有静态列表用户=新列表{
新用户(){id=12345,name=“Bill”},
新用户(){id=12346,name=“Claire”},
新用户(){id=12347,name=“David”}
};
公共静态列表GetUsers()
{
返回用户;
}
公共静态用户GetUser(int-id)
{
返回users.First(user=>user.id==id);
}
}
公共类用户
{
公共int id{get;set;}
公共字符串名称{get;set;}
}
}

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

它很容易配置——可能需要一个小时才能全部启动并运行。它几乎没有什么问题

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


祝你好运

我为这个问题开发了一个开源的NuGet库,它隐式地将EveryMvc/Url转换为每个mvc/Url

虚线URL对SEO更友好,更易于阅读。小写URL通常不会产生太多问题。()

NuGet软件包:

要安装它,只需在VisualStudio中打开NuGet窗口,右键单击项目并选择NuGet Package Manager,然后在“Online”选项卡上键入“小写虚线路由”,它就会弹出

或者,您可以在PackageManager控制台中运行此代码:

安装程序包小写Shedroote

之后,您应该打开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都是小写、虚线和隐式转换的,无需您做更多操作


开源项目Url:

我的这个实现比另一个更幸运。查询字符串在使用Ajax时出现问题。这个实现有点复杂,但值得付出努力。我知道这是一个老版本,但在谷歌上得分很高。GetHttpHandler从未被调用有什么原因吗。我将运行时错误生成代码放在其中,并确保在请求中调用除GetHttpHandler之外的所有方法。
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));
        }
    }
}
<%@ 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>
<%@ 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; }
    }
}
routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);