Kmaczek
Kmaczek

Reputation: 648

Serving static files with Asp.net 5 against Angular SPA

I created SPA with Angular and Asp.net 5. All routes that suppose to be Angular routing paths will return index.html, then Anguar will handle routes further.

When I will type into browser url: http://localhost:12599/user and press enter. Page is created, all static content is requested properly ex. http://localhost:12599/js/app.js and everything works just fine.

Untill... I want to have more complex routes like: http://localhost:12599/user/registration . My index.html is loaded properly but all static content is god damn invoked incorrectly, like this: http://localhost:12599/user/js/app.js . This obviously wont work(404) coz of additional segment /user something stripped out /registration though.

Is there a clean way to handle this. Or i have to do some dirty work in middleware when handling static content?

like this:

IF path.Contains("/js") THEN path = path.stripOutEverythingBefore("/js")

So this will transform http://localhost:12599/user/js/app.js to http://localhost:12599/js/app.js

Some code of my setup so this wont be so dry for you guys:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) //, IRouteBuilder routes
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Request.Path.ToString().Contains("index.html") ||
            SinglePageAppRequestCheck(context))
        {
            // add config cookie
            var webConfig = new WebConfigModel();
            Configuration.Bind(webConfig);
            var jsonSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            context.Response.Cookies.Append("ldmeConfig", JsonConvert.SerializeObject(webConfig, Formatting.None, jsonSettings));
        }

        // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
        // Rewrite request to use app root
        if (SinglePageAppRequestCheck(context))
        {
            context.Request.Path = "/index.html";
            await next();
        }
    });

    app.UseStaticFiles();
}

private static bool SinglePageAppRequestCheck(HttpContext context)
{
    return context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value);
}

Setup is taken from http://benjii.me/2016/01/angular2-routing-with-asp-net-core-1/

Upvotes: 0

Views: 2483

Answers (1)

Kmaczek
Kmaczek

Reputation: 648

Simply add base link to your index, and all relative requests will be done properly

<base href="/">

I knew it, it will be that simple... Took me 3 days to figure that out though :)

Upvotes: 1

Related Questions