Angular Cli Lazy Load WIth MVC5 Application

笑着哭i 提交于 2020-01-02 08:47:27

问题


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:


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 i.e 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 i.e 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.



来源:https://stackoverflow.com/questions/45176297/angular-cli-lazy-load-with-mvc5-application

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