I have SPA, when I'm using routing and want to refresh a page I get 404 because it Client side routing.
How do I handle this?
Here is my routing:
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'index.html'
})
.when('/category/gifts/', {
templateUrl: 'tpl/categories/category-gifts.html',
controller: 'giftsCtrl'
})
.when('/category/gifts/:id', {
templateUrl: 'tpl/categories/category-gifts.html',
controller: 'giftsCtrl'
})
.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
});
For example: http://www.localhost After I enter into http://www.localhost/category/gifts/ and do CTRL + R or hit F5, I get 404, how should I take care about it?
The problem commes from your MVC RouteConfig please update your RegisterRoutes (/app_Start/RouteConfig.cs like below to fix that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Application",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" });
}
}
or option B) if you don't have any controllers you can handle 404 error in your Global.asax just add Application_Error method to it.
protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
HttpException httpException = ex as HttpException;
if (ex != null)
{
int errorCode = httpException.GetHttpCode();
if (errorCode == 404)
{
Response.Redirect("~/");
}
}
}