【问题标题】:Intercept All Relative Paths拦截所有相对路径
【发布时间】:2009-09-18 19:20:00
【问题描述】:

是否可以在评估绝对路径之前拦截应用程序中使用的所有和任何相对路径并删除/编辑其中的一部分?

例子:

在mvc视图页面-

<%= Html.Image("~/{somefolder}/logo.png") %>

我想截取相对路径“~/{somefolder}/logo.png”并将“{somefolder}”替换为通过某种逻辑(数据库、if/else 等)检索到的文件夹位置

【问题讨论】:

  • 你想在什么时候做这个拦截?显示链接到这些资产的页面时?或者当请求进入网络服务器时?
  • 在页面完全输出给访问者之前,任何 url 中的“{somefolder}”的任何和所有实例都将被我想要的东西替换。我认为当相对 url 被解析为绝对的服务器端时,这需要完成,但我不确定。

标签: asp.net-mvc path


【解决方案1】:

您可以创建一个助手来执行此操作。

例如...

public static string LinkedImage(this HtmlHelper html, string url)
{
  Regex regex = new Regex("({(.*?)})");//This is off the top of my head regex which will get strings between the curly brackets/chicken lips/whatever! :).
  var matches = regex.Matches(url);

  foreach (var match in matches)
  {
    //Go get your value from the db or elsewhere
    string newValueFromElsewhere = GetMyValue(match);
    url = url.Replace(string.Format("{{0}}", match), newValueFromElsewhere);
  }

  return html.Image(url);
}

在寻求解析 url 本身方面,您可能希望在 Stephen Walther 的博客中查看 here

【讨论】:

  • 我希望能够替换任何相对“~/”路径 URL 中的 {somefolder}。从您链接的文章中,如果我能以某种方式覆盖 VirtualPathUtility 类(假设一切都通过它),我可以轻松地做到这一点。我会再调查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2012-03-17
  • 1970-01-01
  • 2013-04-10
相关资源
最近更新 更多