ASP.NET Bundles in regular html?

拈花ヽ惹草 提交于 2019-12-20 03:16:37

问题


My angular application is backed by ASP.NET webapi, where I'm serving up an index.html and angular handles everything else from there. I'd like to use bundling, but I can't see how I'd do this. Do I have to use razor (or webforms) just to reference bundles? Or is there an option to give the bundle output a fixed name that I can reference in my src/hrefs?

To clarify, I'm not using MVC or Webforms to serve html. You just get redirected to index.html , and the routing is all client-side. My bundle configuration is done using WebActivator.PostApplicationStartMethod.


回答1:


First, to only answer the question, you can just use a plain link in your html file

<script src='bundles/mybundle' type='text/javascript' language='text/javascript'></script>  

=> that will include your javascript bundle into the page

The problem you will have with this approach is that if you modify a *.js file contained in the bundle, the modification will not be visible in the bundle. This is all about "bundle cache busting", a nice feature of ASP.NET but only usable from a razor template ... Obviously, you cal also restart the pool (but this is quite slow and hard to automate) :)

To workaround the problem, you can define your own ASP.NET MVC Controller with the following

using System.Linq;
using System.Web.Mvc;
using System.Web.Optimization;

namespace Controllers
{
    public class DebugBundlesController : Controller
    {
        // GET: debugbundles/mybundle
        public ActionResult Mybundle()
        {
            return InlineBundleJavaScript("~/bundles/mybundle");
        }

        private ActionResult InlineBundleJavaScript(string bundlePath)
        {
            //see https://blog.mariusschulz.com/2015/10/25/inlining-css-and-javascript-bundles-with-asp-net-mvc
            var bundleContext = new BundleContext(HttpContext, BundleTable.Bundles, "~/bundles");
            var bundle = BundleTable.Bundles.Single(b => b.Path == bundlePath);
            var js = bundle.GenerateBundleResponse(bundleContext).Content;
            return JavaScript(js);
        }
    }
}

and you use that like :

<script src='debugbundles/mybundle' type='text/javascript' language='text/javascript'></script>

=> now, every time you make a change, the bundle will be regenerated.

Be aware to use this only during development because you remove nearly all benefits of bundles (i.e in particular client and server caching)



来源:https://stackoverflow.com/questions/22124153/asp-net-bundles-in-regular-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!