【问题标题】:Append virtual path to incoming url c#将虚拟路径附加到传入的url c#
【发布时间】:2013-07-19 19:57:47
【问题描述】:

是否可以将即将到来的网址更改为 localhost/test?t=gowthamlocalhost/test/t/gowtham

根据我的理解,我想通过扩展来做到这一点

public class Myhandlers : IHttpHandlerFactory
{ 
  public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
  {
    string s= application.Request.QueryString["t"];
    PageParser.GetCompiledPageInstance(url,"/t/"+s, context);
  }
}

我是否在正确的道路上,但我无法实现?或者有没有其他办法?

【问题讨论】:

  • 你真正想做(或学习)什么?可能有更多标准方法可以做到这一点。
  • 只是为了重写所有传入的 url.. 如果应用程序的 url 为 localhost/test,localhost/test/ss.aspx 需要重写为 localhost/test/t/gowtham 和 localhost/test /t/gowtham/ss.aspx
  • 考虑使用现有工具,例如IIS url rewrite

标签: c# .net url-rewriting ihttphandler


【解决方案1】:

每当我做这样的事情时,它一直在使用HttpContext.RewritePath()。快速的'n脏方法是把它放在globabl.asax中,根据请求。 您可以使用Request.Url 获取请求的 URL 的一部分,根据需要进行修改,然后调用 RewritePath。像这样的:

void Application_BeginRequest(object sender, EventArgs e)
{
    string Authority = Request.Url.GetLeftPart(UriPartial.Authority);   // gets the protocol + domain
    string AbsolutePath = Request.Url.AbsolutePath;                     // gets the requested path
    string InsertedPath = string.Empty;                                 // if QS info exists, we'll add this to the URL

    // if 't' exists as a QS key get its value and contruct new path to insert
    if (Request.QueryString["t"] != null && !string.IsNullOrEmpty(Request.QueryString["t"].ToString()))
        InsertedPath = "/t/" + Request.QueryString["t"].ToString();

    string NewUrl = Authority + InsertedPath + AbsolutePath;
    HttpContext.Current.RewritePath(NewUrl);
}

一旦您对它按预期工作感到满意,您就可以将其粘贴到 HttpModule 中。

注意:抱歉,代码不完整,不在开发机器上,无法记住所有 Request.Url 部分。 Intellisense 应该会有所帮助:)

【讨论】:

  • 啊,我重读了您的问题,并认为我误解了。你说 localhost/test?t=gowtham 到 localhost/test/t/gowtham。您是否要获取查询字符串参数(t 和 gowtham)并修改路径以将它们添加为 URL 中的文件夹?或者您是说所有传入的请求都需要添加 /t/gowtham/?
  • s 最初的值是从查询参数中获取的,在我们的例子中,所有传入的 url 都需要有 t/{value form query params} gowtham
  • 我已经更新了我的答案。基本上,它获取当前请求的 URL,将其分解为左侧部分(协议/域)和右侧部分(路径)。然后,它检查查询字符串中的“t”,如果存在,则创建 /t/value (of t),并创建一个新的 URL,其中包含原始域和路径,并在其间插入新路径。然后执行这个新的 URL。
  • 获取“”不是有效的虚拟路径。更改网址后
  • 上面的代码将接受localhost/test?t=gowtham的请求并生成一个localhost/test/t/gowtham的url,我们用它来重写请求的路径。因此localhost/test/t/gowtham 必须存在(或被处理)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 2016-03-11
  • 2011-10-17
相关资源
最近更新 更多