10

I am trying to create an Asp.net WebApi / Single Page Application. I would like my server to dispense index.html if no route is given. I would like it to use a controller when one is specified in the normal "{controller}/{id}" fashion.

I realized that I can visit my index page by using http://localhost:555/index.html. How do I do the same by visiting http://localhost:555 ?

1
  • 2
    if asp.net core just add: app.UseDefaultFiles(); in Startup.cs Configure method. Commented Apr 26, 2018 at 7:10

3 Answers 3

9

Just add a route to your WebApiConfig file for index page. Your method should look like this:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Attribute routing
            config.MapHttpAttributeRoutes();

            // Route to index.html
            config.Routes.MapHttpRoute(
                name: "Index",
                routeTemplate: "{id}.html",
                defaults: new {id = "index"});

            // Default route
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

3

The solution was to create an empty DefaultRoute.

// I think this passes control through before trying to use a Controller
routes.MapHttpRoute(
    "DefaultRoute", "");

routes.MapHttpRoute(
    "DefaultAPI",
    "{controller}/{id}",
    new { Controller = "Home", Id = RouteParameter.Optional });

Another solution was to prefix my WebApi with 'api', which is not entirely what I wanted, but is a suitable solution. This was shown in Herman Guzman's answer, but is not his answer.

// Default route
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }

Comments

0

For ASP.NET Core users

As mentioned in the comments, you can use app.UseDefaultFiles() to achieve this. The method adds a rewriter that rewrites requests to the default route "/" to /index.html. For this to work, it is important that you place this line before .UseStaticFiles(). Example:

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

app.MapControllers();

app.Run();

There is a good blog post that describes how this works in detail: Blog Post

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.