Asp.Net MVC中的高级路由

时间:2016-04-15 14:17:14

标签: c# asp.net-mvc asp.net-mvc-routing

可以在asp.net MVC中创建这样的URL吗?

1

http://url/Home/Function1?name=tomek -> http://url/my-name-tomek
or
http://url/Home/Function1?name=john -> http://url/my-name-john

2

http://url/Home/Function2?name=tomek&address=london -> http://url/my-name-tomek/my-address-london
or
http://url/Home/Function2?name=john&address=york -> http://url/my-name-john/my-address-york

1 个答案:

答案 0 :(得分:0)

那不是“高级路由”。

  1. RouteConfig中:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes(); // <- with this line you enable attribute routing
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    
  2. 在您的控制器中

    namespace TestingUrl.Controllers
    {
        [RoutePrefix("MyController")] // <- Put a special url name for the controller
        public class AnotherController : Controller
        {
            [Route("MyFunction/{name}/{city}")] // <- A special name for the action and the two parameters
            [HttpGet]
            public ActionResult AnotherIndex(string name, string city)
            {
                ViewBag.Name = name;
                ViewBag.City = city;
                return View();
            }
        }
    }
    
  3. 使用此网址进行了测试并有效:

    3.1。本地主机:端口/ MyController / MyFunction /我的名字-安德烈斯/阿雷基帕

    3.2。本地主机:端口/ MyController / MyFunction /我的名字-拉希姆/伊斯兰堡