【问题标题】:How to make a custom route in ASP MVC如何在 ASP MVC 中创建自定义路由
【发布时间】:2017-04-18 00:48:06
【问题描述】:

我正在尝试做这样的事情。

MyUrl.com/ComicBooks/{NameOfAComicBook}

我搞砸了 RouteConfig.cs,但我对此完全陌生,所以我遇到了麻烦。 NameOfAComicBook 是必填参数。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


        routes.MapMvcAttributeRoutes();


        routes.MapRoute("ComicBookRoute",
                            "{controller}/ComicBooks/{PermaLinkName}",
                            new { controller = "Home", action = "ShowComicBook" }
                            );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }
}

HomeController.cs

public ActionResult ShowComicBook(string PermaLinkName)
{


    // i have a breakpoint here that I can't hit


    return View();
}

【问题讨论】:

  • NameOfAComicBook 是可选参数还是强制参数?包括更多细节。
  • @TetsuyaYamamoto 我更新了我的问题。 (强制)
  • 显示您的路线,包括您尝试过的路线,并解释什么不起作用。
  • 您可以发布您当前的RouteConfig.cs 文件吗?
  • 特定路由需要在Default 路由之前 - 并且它需要是"ComicBooks/{PermaLinkName}"(没有{controller}

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


【解决方案1】:

注意到属性路由也已启用。

routes.MapMvcAttributeRoutes();

你也可以直接在控制器中设置路由。

[RoutePrefix("ComicBooks")]
public class ComicBooksController : Controller {    
    [HttpGet]
    [Route("{PermaLinkName}")] //Matches GET ComicBooks/Spiderman
    public ActionResult ShowComicBook(string PermaLinkName){
        //...get comic book based on name
        return View(); //eventually include model with view
    }
}

【讨论】:

  • 我的 ComicBookRoute 有 Controller="Home" 所以我期待它被 HomeController 处理。
猜你喜欢
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2019-01-12
相关资源
最近更新 更多