I need to build a controller action to handle this pattern:
example.com/aString
where aString can be any of a set of arbitrary strings. The controller would cycle thru each of the possible values and, if none match, redirect to a 404.
I'd think it's just a matter of recoding the catch-all but am so far coming up blank. Currently using Sherviniv's suggestion:
//Catchall affiliate shortcuts.
routes.MapRoute(
name: "affLanding",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
Controller:
public ActionResult MatchString(string query)
{
_logger.Info("affLanding: " + query);
return View();
}
If i hard-code my 'search' string into the route.config things work:
routes.MapRoute(
name: "search",
url: "aString",
defaults: new { controller = "home", action = "MatchString"}
);
In routeconfig
routes.MapRoute(
name: "Controller1",
url: "Controller1/{action}/{id}",
defaults: new { controller = "Controller1", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Controller2",
url: "Controller2/{action}/{id}",
defaults: new { controller = "Controller2", action = "Index", id = UrlParameter.Optional }
);
//Other controllers
routes.MapRoute(
name: "search",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
routes.MapRoute(
name: "Default",
url: "",
defaults: new
{
controller = "Home",
action = "Index"
}
);
In your Controller
public ActionResult Index()
{
reutrn view();
}
public ActionResult MatchString(string query)
{
if(Your Condition)
{
//when string query doesnt find
throw new HttpException(404, "Some description");
}
else
{
return view(Your model);
}
}
Remember to add all of your controller's name because if you don't mention them in route config how the server can know it is search parameter or Not. Hope it helps