问题
ASP.NET MVC 4 website.
Got a database-table named "Locations", which holds only three possible Locations (eg. "CA","NY","AT") The default route would be:
http://server/Location/ --- list of Locations
http://server/Location/NY --- details of NY-Location
How can I create a custom route without the /Location/ - bit? (which I find a bit more nice)
So that
http://server/NY - details of NY
http://server/AT - details of AT
.... etc...
and
http://server/Location --- list of Locations
回答1:
A solution is to do a custom route using a route constraint: (the order matters)
routes.MapRoute(
name: "City",
url: "{city}",
constraints: new { city = @"\w{2}" },
defaults: new { controller = "Location", action = "Details", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
with the matching controller:
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
return View();
}
//
// GET: /{city}
public ActionResult Details(string city)
{
return View(model:city);
}
}
If you want to allow only NY, CA and AT you could write you route constraint like:
constraints: new { city = @"NY|CA|AT" }
(lower case works too). Another, more generic solution instead of using a route contraint is to implement your own IRouteConstraint. Se my previous answer.
回答2:
What you need is to specify the route inside your controller. Look at this tutorial on how to specify route constraints:
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs
You use route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.
Also look at this post: How to map a route for /News/5 to my news controller
来源:https://stackoverflow.com/questions/12518388/mvc-4-custom-route