asp.net - How to use short urls for categories in MVC -
short urls containing product categories like
http://example.com/computers
should used in asp.net mvc 4 shopping cart. if there no controller, home index method id parameter computers should called.
i tried add id parameter home controller using
public class homecontroller : mycontrollerbase { public actionresult index(string id) { if (!string.isnullorwhitespace(id)) { return redirecttoaction("browse", "store", new { id = id, }); } return view("index", new homeindexviewmodel()); }
but http://example.com/computers causes 404 error
server error in '/' application.
the resource cannot found.
description: http 404. resource looking (or 1 of dependencies) have been removed, had name changed, or temporarily unavailable. please review following url , make sure spelled correctly.
requested url: /computers
version information: microsoft .net framework version:4.0.30319; asp.net version:4.6.1073.0
how force controller call if there no controller defined after slash in http://example.com/....
mvc default routing used:
public class routeconfig { public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.ignoreroute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" }); routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "home", action = "index", id = urlparameter.optional } ); } }
it looks mvc ignores routing parameter:
defaults: new { controller = "home", action = "index", id = urlparameter.optional }
howe fix ?
your problem because aspnet mvc trying find controller name computers, , controller home, can add new route before route name default:
routes.maproute( name: "computers", url: "computers", defaults: new { controller = "home", action = "index", id = urlparameter.optional } );
in above case, creating route match url http://domain.com/computers , route manage homecontroller.
also, according comment, can have route like:
routes.maproute( name: "default", url: "{id}", defaults: new { controller = "home", action = "index", id = urlparameter.optional } );
Comments
Post a Comment