gpt4 book ai didi

asp.net-mvc - ASP MVC 设置定义图像文件夹

转载 作者:行者123 更新时间:2023-12-02 18:13:01 25 4
gpt4 key购买 nike

我是 asp mvc 的新手,希望在 View 中定义图像/内容文件夹的链接,这样如果图像文件夹发生更改,我就不必更改每个链接。

可以使用 ActionLink 和路由、捆绑,或者有更好的方法来实现这一点。

我在任何地方都找不到一个好的例子,所以我没有尝试任何编码。

我正在考虑在某处存储固定路径,但这真的是 mvc 类型的解决方案吗?

最佳答案

有多种方法可以做到这一点。这是扩展 Url.Content() 方法的一种方法。

1。创建扩展方法

我们将其称为Virtual()

namespace TestApp.Extensions
{
public static class UrlHelperExtensions
{
private const string _settingPattern = "path:{0}";
private const string _regexPattern = @"\{\w+\}";

public static string Virtual(this UrlHelper helper, string url)
{
Regex r = new Regex(_regexPattern);
var matches = r.Matches(url);

if (matches.Count == 0) return url;

var sb = new StringBuilder(url);
var keys = WebConfigurationManager.AppSettings.AllKeys;

foreach (var match in matches)
{
string key = match.ToString().TrimStart('{').TrimEnd('}');
string pattern = string.Format(_settingPattern, key);

foreach (var k in keys)
{
if (k == pattern)
{
sb.Replace(match.ToString(), WebConfigurationManager.AppSettings.Get(k));
}
}
}

return helper.Content(sb.ToString());
}
}
}

2。将设置添加到主 Web.config

自由添加您想要的任何路径。

<add key="path:images" value="~/Content/images" />
<add key="path:scripts" value="~/scripts" />

3。将命名空间添加到 View 目录的 Web.config

<namespaces>
<add namespace="TestApp.Extensions"/>
</namespaces>

4。使用新方法

@Url.Virtual("{images}/mypic.png")

输出:

/Content/images/mypic.png

您现在可以在 Content() 处使用 Virtual()

这个解决方案可以说有些过分,但它很全面。

关于asp.net-mvc - ASP MVC 设置定义图像文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com