0

有没有办法以编程方式呈现脚本包?

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

现在我正在编写一个使用 Self-Host WebApi 的应用程序,我还想在其中创建一个脚本包。也就是说,我在项目中有许多 javascript 文件,我希望将它们缩小、合并,然后根据请求返回。

我想这应该是可能的。不过,似乎找不到任何关于它的信息。

4

1 回答 1

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标头的捆绑内容提供服务。

于 2014-03-02T18:24:10.947 回答