2014-03-02 47 views
0

有没有一种方法来编程渲染脚本包?手动利用MVC脚本捆绑

在MVC中使用脚本包非常棒。喜欢它。用它。

现在我正在编写一个应用程序,使用自我主机WebApi,我也想创建一个脚本包。 也就是说,我在项目中有许多JavaScript文件,我希望将其缩小,合并,然后根据请求返回。

我想这应该是可能的。虽然似乎无法找到任何信息。

回答

2

不幸的是,ASP.NET捆绑机制与ASP.NET上下文紧密结合。在自己的主机上使用它需要一些额外的工作。例如,你需要有将能够从指定位置读取文件自定义虚拟路径提供:

internal class MyVirtualPathProvider : VirtualPathProvider 
{ 
    private readonly string basePath; 
    public MyVirtualPathProvider(string basePath) 
    { 
     this.basePath = basePath; 
    } 

    public override bool FileExists(string virtualPath) 
    { 
     return File.Exists(this.GetFileName(virtualPath)); 
    } 

    public override VirtualFile GetFile(string virtualPath) 
    { 
     return new MyVirtualFile(this.GetFileName(virtualPath)); 
    } 

    private string GetFileName(string virtualPath) 
    { 
     return Path.Combine(this.basePath, virtualPath.Replace("~/", "")); 
    } 

    private class MyVirtualFile : VirtualFile 
    { 
     private readonly string path; 
     public MyVirtualFile(string path) 
      : base(path) 
     { 
      this.path = path; 
     } 

     public override Stream Open() 
     { 
      return File.OpenRead(this.path); 
     } 
    } 
} 

,那么你可以有连接到控制台应用程序,你会注册全部bundle.config文件您的包文件:

<?xml version="1.0" encoding="utf-8" ?> 
<bundles version="1.0"> 
    <scriptBundle path="~/bundles/myBundle"> 
    <include path="~/foo.js" /> 
    <include path="~/bar.js" /> 
    </scriptBundle> 
</bundles> 

下一个你可以写你的自我主机,你将与自定义的,我们刚才写替换默认的虚拟路径提供:

class Program 
{ 
    static void Main() 
    { 
     var config = new HttpSelfHostConfiguration("http://localhost:8080"); 
     config.Routes.MapHttpRoute(
      "API Default", 
      "api/{controller}/{id}", 
      new { id = RouteParameter.Optional } 
     ); 

     BundleTable.VirtualPathProvider = new MyVirtualPathProvider(Environment.CurrentDirectory); 

     using (HttpSelfHostServer server = new HttpSelfHostServer(config)) 
     { 
      server.OpenAsync().Wait(); 
      Console.WriteLine("Press Enter to quit."); 
      Console.ReadLine(); 
     } 
    } 
} 

最后你可能有一些API控制器,它将成为我们在我们的bundle.config文件中定义的自定义捆绑:

public class MyScriptsController: ApiController 
{ 
    public HttpResponseMessage Get() 
    { 
     string bundlePath = "~/bundles/myBundle"; 
     var bundle = BundleTable.Bundles.GetBundleFor(bundlePath); 
     var context = new BundleContext(new HttpContext(), BundleTable.Bundles, bundlePath); 
     var response = bundle.GenerateBundleResponse(context); 
     return new HttpResponseMessage() 
     { 
      Content = new StringContent(response.Content, Encoding.UTF8, "text/javascript"), 
     }; 
    } 

    private class HttpContext : HttpContextBase 
    { 
    } 
} 

在这个例子中,我省略了客户端缓存,你显然应该考虑到内部控制器,以便为相应的Cache标头提供捆绑内容。

+0

Hrm ...看起来有点复杂,我希望。不过谢谢你。一定会试试这个。 –

+0

尝试它,像一个魅力工作!谢谢 – Stephane