【问题标题】:Advanced routing in Asp.Net MVCAsp.Net MVC 中的高级路由
【发布时间】:2016-04-15 14:17:13
【问题描述】:

可以在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

【问题讨论】:

  • Asp.net 没有控制器。你是说 MVC 吗?
  • 您能展示一下到目前为止您尝试过的内容吗?
  • 请查看示例。
  • 如果您愿意,您可以永远删除和重新添加该评论,但是除了您想要做的示例之外,我们还需要看看您自己尝试做些什么来解决问题,即您尝试过的路线。 “是否可以?”它自己永远不会得到答案。 “为什么这段代码不符合我的要求?”可能。
  • 除非你的应用只有一个控制器 (HomeController) 和一种方法 (Function1(string name, string address))

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


【解决方案1】:

这不是“高级路由”。

  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/my-name-Andres/Arequipa

    3.2。 localhost:port/MyController/MyFunction/my-name-Rahim/Islamabad

【讨论】:

    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 2010-12-23
    • 2014-04-08
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多