Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting index.html as default page in asp.net core

How can I get asp.net core to serve an index.html file from inside my wwwroot?

The reason I want to do this is because I an developing an angular 4 app using the angular CLI and it takes care of the entire build process. I have set it up to build into the wwwroot directory of my asp.net core project but asp.net core doesn't want to serve it.

At first I tried to return the html file through a controller. I tried this route:

app.UseMvc(routes =>     {         routes.MapRoute(             name: "default",             template: "{controller=Home}/{action=Index}");     }); 

And then in the controller I return the html file like this:

public IActionResult Index() {     var webRoot = _env.WebRootPath;     var path = System.IO.Path.Combine(webRoot, "index.html");      return File(path, "text/html"); } 

This didn't work. It returned a 404 not found exception and gave the path but the path it gave was the correct path to the index.html file (I cut and pasted it into explorer and the file opened).

I am also declaring these in startup:

app.UseStaticFiles(); app.UseDefaultFiles(); 

I then tried removing the default route. Now I am able to get to the index.html file but only if I type the filename in, i.e.:

localhost:58420/index.html

If I try to access the root of the domain without the "index.html" specified I get a 404 error.

What is the proper way to reference the index.html as the default page? I am guessing doing it from a controller is probably better because then it will be compatible with angular routing without rewrites.

like image 514
Guerrilla Avatar asked Mar 29 '17 10:03

Guerrilla


People also ask

How do I change the default page in ASP NET MVC?

Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table. In MVC 5. if you have a form login, when you click login on the home page, it will then still redirect to Home controller , not your custom controller specified in the route.

What is the default directory for static files in ASP.NET Core?

Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot , but it can be changed with the UseWebRoot method.


1 Answers

Just use this in startup.cs:

app.UseFileServer(); 

It's shorthand for:

app.UseDefaultFiles(); app.UseStaticFiles(); 

it avoids issues with having to have those in the correct order (as shown above)

like image 139
Chris Halcrow Avatar answered Sep 22 '22 00:09

Chris Halcrow