297

私の質問はこれに似ています:

ASP.NET MVC 4 の縮小と背景画像

可能であれば、MVC 独自のバンドルに固執したいことを除いて。スタンドアロンの css や jQuery UI などのイメージ セットが機能するように、スタイル バンドルを指定するための正しいパターンを見つけようとして頭が混乱しています。

/Content/css/などの基本 CSS を含む典型的な MVC サイト構造がありますstyles.css。そのcssフォルダー内に/jquery-uiは、CSSファイルとフォルダーを含むサブフォルダーもあり/imagesます。jQuery UI CSS のイメージ パスは、そのフォルダーに対して相対的であり、それらを台無しにしたくありません。

私が理解しているように、を指定するときはStyleBundle、実際のコンテンツ パスとも一致しない仮想パスを指定する必要があります。これは、(コンテンツへのルートを無視していると仮定して) IIS がそのパスを物理ファイルとして解決しようとするためです。だから私は指定しています:

bundles.Add(new StyleBundle("~/Content/styles/jquery-ui")
       .Include("~/Content/css/jquery-ui/*.css"));

以下を使用してレンダリング:

@Styles.Render("~/Content/styles/jquery-ui")

リクエストが次の場所に送信されていることがわかります。

http://localhost/MySite/Content/styles/jquery-ui?v=nL_6HPFtzoqrts9nwrtjq0VQFYnhMjY5EopXsK8cxmg1

これにより、縮小された正しい CSS 応答が返されます。しかしその後、ブラウザは相対的にリンクされた画像のリクエストを次のように送信します。

http://localhost/MySite/Content/styles/images/ui-bg_highlight-soft_100_eeeeee_1x100.png

これは404.

私の URL の最後の部分はjquery-ui拡張子のない URL、私のバンドルのハンドラーであることを理解しています/styles/images/

だから私の質問は、この状況を処理する正しい方法は何ですか?

4

16 に答える 16

363

MVC4 cssバンドリングとイメージ参照に関するこのスレッドによると、バンドルを次のように定義した場合:

bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
                   .Include("~/Content/css/jquery-ui/*.css"));

バンドルを構成するソースファイルと同じパスでバンドルを定義する場合でも、相対的なイメージパスは機能します。バンドルパスの最後の部分は、実際にfile nameはその特定のバンドル用です(つまり、/bundle任意の名前にすることができます)。

これは、同じフォルダーからCSSをバンドルしている場合にのみ機能します(バンドルの観点からは理にかなっていると思います)。

アップデート

@Hao Kungによる以下のコメントのように、代わりに、(バンドルされている場合はCSSファイルへの相対URL参照を変更する)を適用することでこれを実現CssRewriteUrlTransformationできます

注:仮想ディレクトリ内の絶対パスへの書き換えに関するコメントは確認していないため、すべての人に役立つとは限りません(?)。

bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
                   .Include("~/Content/css/jquery-ui/*.css",
                    new CssRewriteUrlTransform()));
于 2012-07-08T21:47:21.900 に答える
34

Grinn / ThePirat ソリューションはうまく機能します。

バンドルの Include メソッドが新しくなったことと、コンテンツ ディレクトリに一時ファイルが作成されたことが気に入りませんでした。(彼らは最終的にチェックインされ、展開されましたが、サービスは開始されませんでした!)

したがって、Bundling の設計に従うために、基本的に同じコードを実行することにしましたが、IBundleTransform の実装で行いました。

class StyleRelativePathTransform
    : IBundleTransform
{
    public StyleRelativePathTransform()
    {
    }

    public void Process(BundleContext context, BundleResponse response)
    {
        response.Content = String.Empty;

        Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
        // open each of the files
        foreach (FileInfo cssFileInfo in response.Files)
        {
            if (cssFileInfo.Exists)
            {
                // apply the RegEx to the file (to change relative paths)
                string contents = File.ReadAllText(cssFileInfo.FullName);
                MatchCollection matches = pattern.Matches(contents);
                // Ignore the file if no match 
                if (matches.Count > 0)
                {
                    string cssFilePath = cssFileInfo.DirectoryName;
                    string cssVirtualPath = context.HttpContext.RelativeFromAbsolutePath(cssFilePath);
                    foreach (Match match in matches)
                    {
                        // this is a path that is relative to the CSS file
                        string relativeToCSS = match.Groups[2].Value;
                        // combine the relative path to the cssAbsolute
                        string absoluteToUrl = Path.GetFullPath(Path.Combine(cssFilePath, relativeToCSS));

                        // make this server relative
                        string serverRelativeUrl = context.HttpContext.RelativeFromAbsolutePath(absoluteToUrl);

                        string quote = match.Groups[1].Value;
                        string replace = String.Format("url({0}{1}{0})", quote, serverRelativeUrl);
                        contents = contents.Replace(match.Groups[0].Value, replace);
                    }
                }
                // copy the result into the response.
                response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
            }
        }
    }
}

そして、これを Bundle Implemetation にまとめました:

public class StyleImagePathBundle 
    : Bundle
{
    public StyleImagePathBundle(string virtualPath)
        : base(virtualPath)
    {
        base.Transforms.Add(new StyleRelativePathTransform());
        base.Transforms.Add(new CssMinify());
    }

    public StyleImagePathBundle(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath)
    {
        base.Transforms.Add(new StyleRelativePathTransform());
        base.Transforms.Add(new CssMinify());
    }
}

サンプル使用法:

static void RegisterBundles(BundleCollection bundles)
{
...
    bundles.Add(new StyleImagePathBundle("~/bundles/Bootstrap")
            .Include(
                "~/Content/css/bootstrap.css",
                "~/Content/css/bootstrap-responsive.css",
                "~/Content/css/jquery.fancybox.css",
                "~/Content/css/style.css",
                "~/Content/css/error.css",
                "~/Content/validation.css"
            ));

RelativeFromAbsolutePath の拡張メソッドは次のとおりです。

   public static string RelativeFromAbsolutePath(this HttpContextBase context, string path)
    {
        var request = context.Request;
        var applicationPath = request.PhysicalApplicationPath;
        var virtualDir = request.ApplicationPath;
        virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
        return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
    }
于 2012-10-22T20:30:03.160 に答える
20

いっそのこと (IMHO) 画像パスを修正するカスタム バンドルを実装します。アプリ用に作成しました。

using System;
using System.Collections.Generic;
using IO = System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;

...

public class StyleImagePathBundle : Bundle
{
    public StyleImagePathBundle(string virtualPath)
        : base(virtualPath, new IBundleTransform[1]
      {
        (IBundleTransform) new CssMinify()
      })
    {
    }

    public StyleImagePathBundle(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath, new IBundleTransform[1]
      {
        (IBundleTransform) new CssMinify()
      })
    {
    }

    public new Bundle Include(params string[] virtualPaths)
    {
        if (HttpContext.Current.IsDebuggingEnabled)
        {
            // Debugging. Bundling will not occur so act normal and no one gets hurt.
            base.Include(virtualPaths.ToArray());
            return this;
        }

        // In production mode so CSS will be bundled. Correct image paths.
        var bundlePaths = new List<string>();
        var svr = HttpContext.Current.Server;
        foreach (var path in virtualPaths)
        {
            var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
            var contents = IO.File.ReadAllText(svr.MapPath(path));
            if(!pattern.IsMatch(contents))
            {
                bundlePaths.Add(path);
                continue;
            }


            var bundlePath = (IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
            var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
            var bundleFilePath = String.Format("{0}{1}.bundle{2}",
                                               bundlePath,
                                               IO.Path.GetFileNameWithoutExtension(path),
                                               IO.Path.GetExtension(path));
            contents = pattern.Replace(contents, "url($1" + bundleUrlPath + "$2$1)");
            IO.File.WriteAllText(svr.MapPath(bundleFilePath), contents);
            bundlePaths.Add(bundleFilePath);
        }
        base.Include(bundlePaths.ToArray());
        return this;
    }

}

それを使用するには、次のようにします。

bundles.Add(new StyleImagePathBundle("~/bundles/css").Include(
  "~/This/Is/Some/Folder/Path/layout.css"));

...それ以外の...

bundles.Add(new StyleBundle("~/bundles/css").Include(
  "~/This/Is/Some/Folder/Path/layout.css"));

それが行うことは、(デバッグモードでない場合) を探してurl(<something>)、それを に置き換えますurl(<absolute\path\to\something>)。10秒ほど前に書いたので、少し調整が必要かもしれません。URL パスにコロン (:) がないことを確認して、完全修飾 URL と base64 DataURI を考慮しました。私たちの環境では、画像は通常 css ファイルと同じフォルダーにありますが、親フォルダー ( url(../someFile.png)) と子フォルダー ( ) の両方でテストしましたurl(someFolder/someFile.png

于 2012-10-02T18:41:30.330 に答える
12

たぶん私は偏っていますが、変換や正規表現などを行わず、コードの量が最小限であるため、私のソリューションが非常に気に入っています:)

これは、IIS Web サイトで仮想ディレクトリとしてホストされ、IIS でルート Web サイトとしてホストされているサイトで機能します。

そこで、IItemTransformカプセル化されたの実装を作成し、パスを修正して既存のコードを呼び出すためにCssRewriteUrlTransform使用しました。VirtualPathUtility

/// <summary>
/// Is a wrapper class over CssRewriteUrlTransform to fix url's in css files for sites on IIS within Virutal Directories
/// and sites at the Root level
/// </summary>
public class CssUrlTransformWrapper : IItemTransform
{
    private readonly CssRewriteUrlTransform _cssRewriteUrlTransform;

    public CssUrlTransformWrapper()
    {
        _cssRewriteUrlTransform = new CssRewriteUrlTransform();
    }

    public string Process(string includedVirtualPath, string input)
    {
        return _cssRewriteUrlTransform.Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
    }
}


//App_Start.cs
public static void Start()
{
      BundleTable.Bundles.Add(new StyleBundle("~/bundles/fontawesome")
                         .Include("~/content/font-awesome.css", new CssUrlTransformWrapper()));
}

私にとってはうまくいくようですか?

于 2015-06-16T14:46:37.093 に答える
11

*.cssファイルを参照していて、関連付けられている*.min.cssファイルが同じフォルダーにある場合、CssRewriteUrlTransform の実行に失敗することがわかりました。

これを修正するには、*.min.cssファイルを削除するか、バンドルで直接参照します。

bundles.Add(new Bundle("~/bundles/bootstrap")
    .Include("~/Libs/bootstrap3/css/bootstrap.min.css", new CssRewriteUrlTransform()));

その後、URL が正しく変換され、画像が正しく解決されるはずです。

于 2014-12-12T00:18:42.753 に答える
7

Chris Baxter の回答は元の問題に役立ちますが、私の場合、アプリケーションが仮想ディレクトリでホストされている場合は機能しません。オプションを検討した後、DIYソリューションで終了しました。

ProperStyleBundleCssRewriteUrlTransformクラスには、仮想ディレクトリ内の相対パスを適切に変換するためにオリジナルから借用したコードが含まれています。また、ファイルが存在しない場合にもスローし、バンドル内のファイルの並べ替えを防ぎます (コードは から取得BetterStyleBundle)。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;
using System.Linq;

namespace MyNamespace
{
    public class ProperStyleBundle : StyleBundle
    {
        public override IBundleOrderer Orderer
        {
            get { return new NonOrderingBundleOrderer(); }
            set { throw new Exception( "Unable to override Non-Ordered bundler" ); }
        }

        public ProperStyleBundle( string virtualPath ) : base( virtualPath ) {}

        public ProperStyleBundle( string virtualPath, string cdnPath ) : base( virtualPath, cdnPath ) {}

        public override Bundle Include( params string[] virtualPaths )
        {
            foreach ( var virtualPath in virtualPaths ) {
                this.Include( virtualPath );
            }
            return this;
        }

        public override Bundle Include( string virtualPath, params IItemTransform[] transforms )
        {
            var realPath = System.Web.Hosting.HostingEnvironment.MapPath( virtualPath );
            if( !File.Exists( realPath ) )
            {
                throw new FileNotFoundException( "Virtual path not found: " + virtualPath );
            }
            var trans = new List<IItemTransform>( transforms ).Union( new[] { new ProperCssRewriteUrlTransform( virtualPath ) } ).ToArray();
            return base.Include( virtualPath, trans );
        }

        // This provides files in the same order as they have been added. 
        private class NonOrderingBundleOrderer : IBundleOrderer
        {
            public IEnumerable<BundleFile> OrderFiles( BundleContext context, IEnumerable<BundleFile> files )
            {
                return files;
            }
        }

        private class ProperCssRewriteUrlTransform : IItemTransform
        {
            private readonly string _basePath;

            public ProperCssRewriteUrlTransform( string basePath )
            {
                _basePath = basePath.EndsWith( "/" ) ? basePath : VirtualPathUtility.GetDirectory( basePath );
            }

            public string Process( string includedVirtualPath, string input )
            {
                if ( includedVirtualPath == null ) {
                    throw new ArgumentNullException( "includedVirtualPath" );
                }
                return ConvertUrlsToAbsolute( _basePath, input );
            }

            private static string RebaseUrlToAbsolute( string baseUrl, string url )
            {
                if ( string.IsNullOrWhiteSpace( url )
                     || string.IsNullOrWhiteSpace( baseUrl )
                     || url.StartsWith( "/", StringComparison.OrdinalIgnoreCase )
                     || url.StartsWith( "data:", StringComparison.OrdinalIgnoreCase )
                    ) {
                    return url;
                }
                if ( !baseUrl.EndsWith( "/", StringComparison.OrdinalIgnoreCase ) ) {
                    baseUrl = baseUrl + "/";
                }
                return VirtualPathUtility.ToAbsolute( baseUrl + url );
            }

            private static string ConvertUrlsToAbsolute( string baseUrl, string content )
            {
                if ( string.IsNullOrWhiteSpace( content ) ) {
                    return content;
                }
                return new Regex( "url\\(['\"]?(?<url>[^)]+?)['\"]?\\)" )
                    .Replace( content, ( match =>
                                         "url(" + RebaseUrlToAbsolute( baseUrl, match.Groups["url"].Value ) + ")" ) );
            }
        }
    }
}

次のように使用しますStyleBundle

bundles.Add( new ProperStyleBundle( "~/styles/ui" )
    .Include( "~/Content/Themes/cm_default/style.css" )
    .Include( "~/Content/themes/custom-theme/jquery-ui-1.8.23.custom.css" )
    .Include( "~/Content/DataTables-1.9.4/media/css/jquery.dataTables.css" )
    .Include( "~/Content/DataTables-1.9.4/extras/TableTools/media/css/TableTools.css" ) );
于 2015-01-11T19:03:27.503 に答える
6

v1.1.0-alpha1(プレリリースパッケージ)以降、フレームワークはVirtualPathProvider、物理ファイルシステムにアクセスするのではなく、を使用してファイルにアクセスします。

更新されたトランスフォーマーは以下のとおりです。

public class StyleRelativePathTransform
    : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);

        response.Content = string.Empty;

        // open each of the files
        foreach (var file in response.Files)
        {
            using (var reader = new StreamReader(file.Open()))
            {
                var contents = reader.ReadToEnd();

                // apply the RegEx to the file (to change relative paths)
                var matches = pattern.Matches(contents);

                if (matches.Count > 0)
                {
                    var directoryPath = VirtualPathUtility.GetDirectory(file.VirtualPath);

                    foreach (Match match in matches)
                    {
                        // this is a path that is relative to the CSS file
                        var imageRelativePath = match.Groups[2].Value;

                        // get the image virtual path
                        var imageVirtualPath = VirtualPathUtility.Combine(directoryPath, imageRelativePath);

                        // convert the image virtual path to absolute
                        var quote = match.Groups[1].Value;
                        var replace = String.Format("url({0}{1}{0})", quote, VirtualPathUtility.ToAbsolute(imageVirtualPath));
                        contents = contents.Replace(match.Groups[0].Value, replace);
                    }

                }
                // copy the result into the response.
                response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
            }
        }
    }
}
于 2012-11-30T12:04:55.740 に答える
5

これは、CSS URL をその CSS ファイルに関連する URL に置き換える Bundle Transform です。バンドルに追加するだけで、問題が解決するはずです。

public class CssUrlTransform: IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response) {
        Regex exp = new Regex(@"url\([^\)]+\)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (FileInfo css in response.Files) {
            string cssAppRelativePath = css.FullName.Replace(context.HttpContext.Request.PhysicalApplicationPath, context.HttpContext.Request.ApplicationPath).Replace(Path.DirectorySeparatorChar, '/');
            string cssDir = cssAppRelativePath.Substring(0, cssAppRelativePath.LastIndexOf('/'));
            response.Content = exp.Replace(response.Content, m => TransformUrl(m, cssDir));
        }
    }


    private string TransformUrl(Match match, string cssDir) {
        string url = match.Value.Substring(4, match.Length - 5).Trim('\'', '"');

        if (url.StartsWith("http://") || url.StartsWith("data:image")) return match.Value;

        if (!url.StartsWith("/"))
            url = string.Format("{0}/{1}", cssDir, url);

        return string.Format("url({0})", url);
    }

}
于 2013-03-26T13:00:29.303 に答える
4

もう 1 つのオプションは、IIS URL 書き換えモジュールを使用して、仮想バンドル イメージ フォルダーを物理イメージ フォルダーにマップすることです。以下は、「~/bundles/yourpage/styles」というバンドルに使用できる書き換えルールの例です。正規表現は、画像ファイル名で一般的なハイフン、アンダースコア、ピリオドだけでなく、英数字にも一致することに注意してください。 .

<rewrite>
  <rules>
    <rule name="Bundle Images">
      <match url="^bundles/yourpage/images/([a-zA-Z0-9\-_.]+)" />
      <action type="Rewrite" url="Content/css/jquery-ui/images/{R:1}" />
    </rule>
  </rules>
</rewrite>

この方法ではオーバーヘッドが少し増えますが、バンドル名をより詳細に制御できるようになり、1 ページで参照する必要があるバンドルの数も減ります。もちろん、相対イメージ パス参照を含む複数のサード パーティの css ファイルを参照する必要がある場合でも、複数のバンドルを作成することはできません。

于 2012-09-12T19:54:33.713 に答える
4

グリンのソリューションは素晴らしいです。

ただし、URLに親フォルダーの相対参照がある場合は機能しません。すなわちurl('../../images/car.png')

Includeそのため、各正規表現一致のパスを解決するためにメソッドを少し変更し、相対パスを許可し、必要に応じて CSS に画像を埋め込むこともできました。

BundleTable.EnableOptimizationsまた、IF DEBUG をの代わりにcheck に変更しましたHttpContext.Current.IsDebuggingEnabled

    public new Bundle Include(params string[] virtualPaths)
    {
        if (!BundleTable.EnableOptimizations)
        {
            // Debugging. Bundling will not occur so act normal and no one gets hurt. 
            base.Include(virtualPaths.ToArray());
            return this;
        }
        var bundlePaths = new List<string>();
        var server = HttpContext.Current.Server;
        var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
        foreach (var path in virtualPaths)
        {
            var contents = File.ReadAllText(server.MapPath(path));
            var matches = pattern.Matches(contents);
            // Ignore the file if no matches
            if (matches.Count == 0)
            {
                bundlePaths.Add(path);
                continue;
            }
            var bundlePath = (System.IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
            var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
            var bundleFilePath = string.Format("{0}{1}.bundle{2}",
                                               bundlePath,
                                               System.IO.Path.GetFileNameWithoutExtension(path),
                                               System.IO.Path.GetExtension(path));
            // Transform the url (works with relative path to parent folder "../")
            contents = pattern.Replace(contents, m =>
            {
                var relativeUrl = m.Groups[2].Value;
                var urlReplace = GetUrlReplace(bundleUrlPath, relativeUrl, server);
                return string.Format("url({0}{1}{0})", m.Groups[1].Value, urlReplace);
            });
            File.WriteAllText(server.MapPath(bundleFilePath), contents);
            bundlePaths.Add(bundleFilePath);
        }
        base.Include(bundlePaths.ToArray());
        return this;
    }


    private string GetUrlReplace(string bundleUrlPath, string relativeUrl, HttpServerUtility server)
    {
        // Return the absolute uri
        Uri baseUri = new Uri("http://dummy.org");
        var absoluteUrl = new Uri(new Uri(baseUri, bundleUrlPath), relativeUrl).AbsolutePath;
        var localPath = server.MapPath(absoluteUrl);
        if (IsEmbedEnabled && File.Exists(localPath))
        {
            var fi = new FileInfo(localPath);
            if (fi.Length < 0x4000)
            {
                // Embed the image in uri
                string contentType = GetContentType(fi.Extension);
                if (null != contentType)
                {
                    var base64 = Convert.ToBase64String(File.ReadAllBytes(localPath));
                    // Return the serialized image
                    return string.Format("data:{0};base64,{1}", contentType, base64);
                }
            }
        }
        // Return the absolute uri 
        return absoluteUrl;
    }

お役に立てば幸いです。

于 2012-10-19T23:03:18.567 に答える
2

仮想バンドル パスに別のレベルの深さを追加するだけです。

    //Two levels deep bundle path so that paths are maintained after minification
    bundles.Add(new StyleBundle("~/Content/css/css").Include("~/Content/bootstrap/bootstrap.css", "~/Content/site.css"));

これは非常にローテクな答えであり、一種のハックですが、機能し、前処理は必要ありません。これらの回答のいくつかの長さと複雑さを考えると、私はこのようにすることを好みます。

于 2013-12-23T21:21:18.467 に答える
2

バンドルの画像へのパスが正しくなく、CssRewriteUrlTransform相対親パス..を正しく解決できないという問題がありました (Web フォントなどの外部リソースにも問題がありました)。そのため、このカスタム トランスフォームを作成しました (上記のすべてを正しく実行しているように見えます)。

public class CssRewriteUrlTransform2 : IItemTransform
{
    public string Process(string includedVirtualPath, string input)
    {
        var pathParts = includedVirtualPath.Replace("~/", "/").Split('/');
        pathParts = pathParts.Take(pathParts.Count() - 1).ToArray();
        return Regex.Replace
        (
            input,
            @"(url\(['""]?)((?:\/??\.\.)*)(.*?)(['""]?\))",
            m => 
            {
                // Somehow assigning this to a variable is faster than directly returning the output
                var output =
                (
                    // Check if it's an aboslute url or base64
                    m.Groups[3].Value.IndexOf(':') == -1 ?
                    (
                        m.Groups[1].Value +
                        (
                            (
                                (
                                    m.Groups[2].Value.Length > 0 ||
                                    !m.Groups[3].Value.StartsWith('/')
                                )
                            ) ?
                            string.Join("/", pathParts.Take(pathParts.Count() - m.Groups[2].Value.Count(".."))) :
                            ""
                        ) +
                        (!m.Groups[3].Value.StartsWith('/') ? "/" + m.Groups[3].Value : m.Groups[3].Value) +
                        m.Groups[4].Value
                    ) :
                    m.Groups[0].Value
                );
                return output;
            }
        );
    }
}

編集:私はそれを認識していませんでしたが、コードでいくつかのカスタム拡張メソッドを使用しました。それらのソースコードは次のとおりです。

/// <summary>
/// Based on: http://stackoverflow.com/a/11773674
/// </summary>
public static int Count(this string source, string substring)
{
    int count = 0, n = 0;

    while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
    {
        n += substring.Length;
        ++count;
    }
    return count;
}

public static bool StartsWith(this string source, char value)
{
    if (source.Length == 0)
    {
        return false;
    }
    return source[0] == value;
}

もちろん、と交換できるはずString.StartsWith(char)ですString.StartsWith(string)

于 2014-11-05T13:45:53.723 に答える
1

少し調査した後、次の結論に達しました。2 つのオプションがあります。

  1. 変換を行います。これには非常に便利なパッケージ: https://bundletransformer.codeplex.com/ 問題のあるバンドルごとに次の変換が必要です:

    BundleResolver.Current = new CustomBundleResolver();
    var cssTransformer = new StyleTransformer();
    standardCssBundle.Transforms.Add(cssTransformer);
    bundles.Add(standardCssBundle);
    

利点: このソリューションでは、バンドルに好きな名前を付けることができます => css ファイルを異なるディレクトリから 1 つのバンドルに結合できます。短所: 問題のあるすべてのバンドルを変換する必要があります

  1. css ファイルが配置されている場所と同様に、バンドルの名前に同じ相対ルートを使用します。利点: 変換の必要はありません。短所: 異なるディレクトリの css シートを 1 つのバンドルに結合することには制限があります。
于 2016-01-07T20:29:39.837 に答える
0

CssRewriteUrlTransform私の問題を修正しました。
を使用した後もコードが画像をロードしない場合はCssRewriteUrlTransform、css ファイル名を次のように変更します。

.Include("~/Content/jquery/jquery-ui-1.10.3.custom.css", new CssRewriteUrlTransform())

に:

.Include("~/Content/jquery/jquery-ui.css", new CssRewriteUrlTransform())

どういうわけか .(ドット) が URL で認識されません。

于 2015-09-10T08:23:09.273 に答える