Reputation: 5464
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 ?
Upvotes: 10
Views: 11987
Reputation: 1118
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
Upvotes: 0
Reputation: 5464
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 }
Upvotes: 3
Reputation: 1235
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 }
);
}
}
Upvotes: 9