5

我想知道是否有一种简单的方法可以为我在视图中通过 Url.Content 引用的所有内容指定 CDN。

我可以以类似于以下方式在我的 Web.config 文件中配置的东西。

    <cdn>
        <add filetype="css" root="http://mycdn.mydomain.com/stylesheets/" />
        <add filetype="js" root="http://myjscdn.mydomain.com/js/ />
    </cdn>

然后,我可以只拥有 <%= Url.Content("~/Content/StyleSheets/What.css") %> 并且它会输出http://mycdn.mydomain.com/stylesheets/Content/StyleSheets/What.css .

如果没有可用的东西,我会通过扩展方法自己做,但我想知道它是否可以开箱即用。

4

2 回答 2

9

上面的答案可能是正确的,下面是它在实践中的样子:

// @ UrlHelperExtensions.cs

public static class UrlHelperExtensions 
{ 
    public static string CdnContent(this UrlHelper helper, string contentPath)
    {
        return (ConfigurationManager.AppSettings["CDN_Available"] == "True")
              ? ConfigurationManager.AppSettings["CDN_ContentRootUrl"] 
                   + contentPath.TrimStart('~')
              : helper.Content(contentPath);
}

// @ Web.config 

<appSettings>
    // ...
    <add key="CDN_Available" value="True" />
    <add key="CDN_SiteImageRoot" value="http://cdn.gbase.com/images/" />
    // ...
</appSettings>

// @ MyPage.cs

<link href="@Url.CdnContent("~/client/css/mymin.css")" rel="stylesheet" type="text/css" media="all" />

我认为这行得通。您还可以使用多种扩展方法来隔离各种内容以在本地和 CDN 上提供服务。但并不要求配置在 web.config 中,只对开发和管理有用。

于 2011-05-06T16:21:10.130 回答
0

I don't believe there is anything built in to facilitate this for you. That said, is adding this to Web.config really necessary?

I guess if you don't want to include your CDN-distributed items on every page in your application, I could understand extrapolating the URLs to a central location somewhere, but even then it seems like you could just write some extension methods that return a constant string instead of messing with the Web.config. I know some people cringe at this because you have to recompile to change the URL's, but how often are they going to change?

In the event, however, that you do want to include these CDN-distributed items on every page, what's wrong with throwing the URLs in your master page? In most cases, changing your master page is just as simple as changing a web.config value.

于 2010-01-05T15:37:28.280 回答