【问题标题】:How to add username in URL (i.e. URL Rewriting)?如何在 URL 中添加用户名(即 URL 重写)?
【发布时间】:2012-06-01 14:48:15
【问题描述】:

我想在成功注册/登录后在url中输入用户的用户名,像这样

http://myweb.com/username/255
http://myweb.com/username/settings

我正在使用 ASP.Net Rewrite 模块,这是我目前使用的生成 http://myweb.com/home/255 的重写规则之一:

<rule name="HomeRewrite" stopProcessing="true">
    <match url="^home$"/>
    <conditions>
        <add input="{URL}" pattern="\.axd$" negate="true"/>
    </conditions>
    <action type="Rewrite" url="/home.aspx"/>
</rule>

我试着像这样改变自己:

<rule name="HomeRewrite" stopProcessing="true">
    <match url="^{R:1}/home$"/>
    <conditions>
        <add input="{URL}" pattern="\.axd$" negate="true"/>
    </conditions>
    <action type="Rewrite" url="/home.aspx"/>
</rule>

但它不起作用,我知道我做错了。那么在这方面有什么帮助吗?

【问题讨论】:

  • 为什么不使用页面路由?我有一些页面路由代码将用户名添加到路由数据中。还是您希望浏览器地址栏中的 URL 发生变化?

标签: asp.net url-rewriting


【解决方案1】:

虽然 ASP.NET Routing 是 MVC 的一部分,但您也可以在 ASP.Net 表单应用程序中使用该机制(参见 http://www.4guysfromrolla.com/articles/051309-1.aspx

例如在 Global.asax 的空白处Application_Start(object sender, EventArgs e) 您可以添加此代码

RouteTable.Routes.Add("Users", new Route("{username}/settings", 
new CustomRouteHandler()));

自定义类 CustomRouteHandler 实现 IRouteHandler 将请求发送到您的设置代码(视图)。

您只需要在用户通过身份验证后立即将他重定向到该网址(并将他留在那里)在 Global.asax 的Application_BeginRequest(object sender, EventArgs e)

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多