How to redirect EVERYTHING except web API to / index.html

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(""); //Allow index.html to load routes.IgnoreRoute("partials/*"); routes.IgnoreRoute("assets/*"); } } 

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" /> <!-- Allows for routing everything to ~/index.html --> ... </buildProviders> </compilation> ... </system.web> 

However, it smells of blush. Any better way to do this?

+48
angularjs c # asp.net-mvc asp.net-mvc-4
Oct 28 '13 at 19:03
source share
5 answers

Use a wildcard segment:

 routes.MapRoute( name: "Default", url: "{*anything}", defaults: new { controller = "Home", action = "Index" } ); 
+24
Oct 28 '13 at 19:10
source share

Suggest a more convenient approach.

 <system.webServer> <httpErrors errorMode="Custom"> <remove statusCode="404" subStatusCode="-1"/> <error statusCode="404" prefixLanguageFilePath="" path="/index.cshtml" responseMode="ExecuteURL"/> </httpErrors> </system.webServer> 
+11
Jun 17 '14 at 9:48
source share

in my case, none of these approaches worked. I am stuck in 2 error messages. either this page type is not served or some 404.

Work with URL:

 <system.webServer> <rewrite> <rules> <rule name="AngularJS" stopProcessing="true"> <match url="[a-zA-Z]*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> ... 

Note that I am mapped to [a-zA-Z] because I do not want to rewrite any of the .js.map URLs, etc.

this worked in VS outside the hte field, but in IIS you may need to install the url-rewrite module https://www.iis.net/downloads/microsoft/url-rewrite

+4
04 Oct '16 at 20:15
source share

I had the same approach as the most correct answers, but the disadvantage is that if someone calls the API incorrectly, they will return this index page instead of something more useful.

So, I updated mine so that it returns my index page for any request not starting with / api:

  //Web Api GlobalConfiguration.Configure(config => { config.MapHttpAttributeRoutes(); }); //MVC RouteTable.Routes.Ignore("api/{*anything}"); RouteTable.Routes.MapPageRoute("AnythingNonApi", "{*url}", "~/wwwroot/index.html"); 
+3
02 Feb '17 at 18:39
source share

Well, I just deleted the call to RouteConfig.RegisterRoutes(RouteTable.Routes); in Global.asax.cs and now any URL that I entered, if the resource exists, it will be served. Even the API help pages still work.

0
Feb 18 '16 at 13:47
source share



All Articles