2014-05-05 1 views
2

Я работаю на одном приложении страницы, которая использует CSS сверток в .cshtml файл, как показано ниже:Как извлечь вывод стиля или Javascript Bundle в ASP.NET

@ Styles.Render (» ~/content/css/bundle-css ")

Однако, чтобы повысить производительность загрузки сайта, я хотел бы встроить весь CSS, который был связан и проинсталлирован в мой .cshtml-файл. Поэтому хотел бы преобразовать код выше, чтобы выглядеть так:

@ Html.GetInternalCss ("~/content/css/bundle-css");

Где GetInternalCss - это метод расширения, который будет принимать виртуальный путь css и выводить внутренний css. Код показан ниже:

public static MvcHtmlString GetInternalCss(this HtmlHelper html, string styleBundleVirtualPath) 
    { 
     //TODO: 
     var bundledCss = "How do I extract the css from the virtual path?"; 

     var internalCss = string.Format("<style>{0}</style>", bundledCss); 

     return new MvcHtmlString(internalCss); 


    } 

Я знаю, что связанный css находится где-то в памяти. Мне просто нужно знать, как это сделать. Спасибо за вашу помощь.

+0

Не могли бы вы добавите в качестве ответа, а не как редактировать? – christo8989

+0

@ christo8989 Готово – Kess

ответ

0

я, возможно, ответил на свой вопрос на код ниже:

using System.Collections.Concurrent; 
    using System.Collections.Generic; 
    using System.Net; 
    using System.Web.Mvc; 
    using System.Web.Optimization; 

    namespace SomeNameSpace 
    { 

     public static class HtmlHelpExtensions 
     { 
      private static readonly IDictionary<string,string> InternalCssCache = new ConcurrentDictionary<string, string>(); 

      public static MvcHtmlString GetInternalCss(this HtmlHelper html, string styleBundleVirtualPath) 
      { 
       string internalCss = null; 
       if (InternalCssCache.TryGetValue(styleBundleVirtualPath, out internalCss)) 
        return new MvcHtmlString(internalCss); 

       //download the css 
       var relativeUrl = Styles.Url(styleBundleVirtualPath); 
       var url = html.ViewContext.HttpContext.Request.Url + relativeUrl.ToString().Trim('/'); 
       var webClient = new WebClient(); 
       var css = webClient.DownloadString(url); 

       internalCss = string.Format("<style>{0}</style>", css); 
       InternalCssCache[styleBundleVirtualPath] = internalCss; 

       return new MvcHtmlString(internalCss); 
      } 
     } 

    } 

 Смежные вопросы

  • Нет связанных вопросов^_^