The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true)
is set.
This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do
Set the <base>
element properly
<base href="@(Request.ApplicationPath + "/")">
First redirect 404 to a custom page, for example "Home/Error"
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Error" />
</customErrors>
</system.web>
Implement a simple ActionResult
to "translate" input in a clientside route.
public ActionResult Error(string aspxerrorpath) {
return this.Redirect("~/#/" + aspxerrorpath);
}
This is the simplest way.
It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes
.when("/", {
templateUrl: "Base/Home",
controller: "controllerHome"
})
.when("/New", {
templateUrl: "Base/New",
controller: "controllerNew"
})
.when("/Show/:title", {
templateUrl: "Base/Show",
controller: "controllerShow"
})
It makes sense to redirect URL to client only when it start with "/New" or "/Show/"
public ActionResult Error(string aspxerrorpath) {
// get clientside route path
string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
// create a set of valid clientside path
string[] validPaths = { "/New", "/Show/" };
// check if clientPath is valid and redirect properly
foreach (string validPath in validPaths) {
if (clientPath.StartsWith(validPath)) {
return this.Redirect("~/#/" + clientPath);
}
}
return new HttpNotFoundResult();
}
This is just an example of improved logic, of course every web application has different needs