简体   繁体   中英

Angular Cli Lazy Load WIth MVC5 Application

I am building MVC5 application with Angular 4 and I am using Angular Cli to create angular app.

The problem I am facing I have MVC5 application running on port 5011 while angular app using angular cli using a port 4200. When I run the MVC application everything work fine except lazy loaded module.

Because lazy loaded module create chunks.js and those chunks are giving error not found. But all other js loaded successfully.

Here is the problem loading chunks.js

My MVC application use port 5011 Angular cli app use port 4200 I reference js files in my _Layout.cshtml are as follows

<script type="text/javascript" src="http://localhost:4200/inline.bundle.js"></script>
        <script type="text/javascript" src="http://localhost:4200/polyfills.bundle.js"></script>
        <script type="text/javascript" src="http://localhost:4200/styles.bundle.js"></script>
        <script type="text/javascript" src="http://localhost:4200/vendor.bundle.js"></script>
        <script type="text/javascript" src="http://localhost:4200/main.bundle.js"></script>

While chunks.js try to load from this url automatically

http://localhost:5011/0.chunk.js

Why is chunks port different than Angular cli port? how to resolve this issue?

1) Add Following in web.config

<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0_2"
path="/*"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

Tell iis to handle paths with dots ie 0.chunk.js

2) Add Following in App_Start/RouterConfig.cs

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
        name: "Redirect",
        url: "{*.url}",
        defaults: new { controller = "Home", action = "Index" }
        );

    }

Tell Router to redirect all requests to index of home controller

3) Add Following in HomeController Index Method

public ActionResult Index()
    {
        var a = Request.Url.AbsoluteUri.ToString();
        var b = Request.RawUrl.ToString();
        if(b!="/") return Redirect("http://localhost:4200"+b);
        return View();
    }

Tell index method to redirect any request containing any other file name to localhost:4200

What actually happening is our index.cshtml is making request to itself wherease our chunks are being served at other server ie localhost:4200 , So what we are doing here is , we are redirecting all request containing chunks in their path to localhost:4200.

It is tested verified and working solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM