I was working on an AngularJS project inside ASP.NET MVC using the web API. It works great unless you are trying to go directly to the angular url or refresh the page. Instead of disarming the server configuration, I thought it would be something that I could handle using the MVC routing mechanism .
Current WebAPIConfig:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { id = @"^[0-9]+$" } ); config.Routes.MapHttpRoute( name: "ApiWithActionAndName", routeTemplate: "api/{controller}/{action}/{name}", defaults: null, constraints: new { name = @"^[az]+$" } ); config.Routes.MapHttpRoute( name: "ApiWithAction", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Get" } ); } }
Current RouteConfig:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("");
Current Global.asax.cs:
public class WebApiApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, }; } }
A TASK:
/ api / * still goes to WebAPI, / partials / and / assets / all goes to the file system, absolutely anything else is redirected to /index.html, which is my angular one-page application.
- EDIT -
I think I got a job. Added this to the BOTTOM OF RouteConfig.cs:
routes.MapPageRoute("Default", "{*anything}", "~/index.html");
And this is a change in the root web.config:
<system.web> ... <compilation debug="true" targetFramework="4.5.1"> <buildProviders> ... <add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> ... </buildProviders> </compilation> ... </system.web>
However, it smells of blush. Any better way to do this?