如何将后代 UrlHelper 类注入到 WebViewPage 中以启用缓存无效化

本文关键字:启用 缓存 无效 WebViewPage 后代 UrlHelper 注入 | 更新日期: 2023-09-27 18:28:18

我已经覆盖了UrlHelper.Content()方法。现在我希望使用我的实现而不是默认的UrlHelper类。

如何配置 MVC 以告诉它要注入到WebViewPage.Url属性中的类?

更新 1:
这个想法很简单。捆绑包通过向 url 添加时间戳查询参数来支持缓存无效化。
我希望单个资源具有相同的功能。
UrlHelper类允许覆盖其Content(string)方法。因此,在生成最终字符串时可以考虑资源的时间戳。

更新 2:
看来我的前提是争吵。我喊出那个src="~..."等效于 src="@Url.Content("~..."("。事实并非如此。

如何将后代 UrlHelper 类注入到 WebViewPage 中以启用缓存无效化

你需要引入你自己的WebViewPage,它提供了自己的UrlHelper实现,这将覆盖Content()方法。

首先,创建类型:

public class MyUrlHelper : UrlHelper
{
    public MyUrlHelper() {}
    public MyUrlHelper(RequestContext requestContext) : base(requestContext) {}
    public MyUrlHelper(RequestContext requestContext, RouteCollection routeCollection) : base(requestContext, routeCollection) { }
    public override string Content(string contentPath)
    {
        // do your own custom implemetation here,
        // you access original Content() method using base.Content()
    }
}
public abstract class MyWebPage : WebViewPage
{
    protected override void InitializePage()
    {
        this._urlHelper = new MyUrlHelper(this.Request.RequestContext, RouteTable.Routes);
    }
    private MyUrlHelper _urlHelper;
    public new MyUrlHelper Url { get { return _urlHelper; } }
}
// provide generic version for strongly typed views
public abstract class MyWebPage<T> : WebViewPage<T>
{
    protected override void InitializePage()
    {
        this._urlHelper = new MyUrlHelper(this.Request.RequestContext, RouteTable.Routes);
    }
    private MyUrlHelper _urlHelper;
    public new MyUrlHelper Url { get { return _urlHelper; } }
}

然后在~/Views/Web.Config中注册您的自定义MyWebPage

  <system.web.webPages.razor>
    ....
    <pages pageBaseType="Your.NameSpace.MyWebPage">
         ....
    </pages>
  </system.web.webPages.razor>

我没有直接回答你的问题,但你可以像这样创建 URLHelper 类的扩展:

public static class CustomUrlHelper
{
    public static string CustomContent(this UrlHelper helper, string contentPath)
    {
        // your Content method 
    }
}

然后只需在Url对象上调用此方法,如下所示:

@Url.CustomContent("~/Content/Site.css")