How to make a custom route in ASP MVC

不羁岁月 提交于 2019-12-04 03:30:06

问题


I'm trying to do something like this.

MyUrl.com/ComicBooks/{NameOfAComicBook}

I messed around with RouteConfig.cs but I'm completely new at this, so I'm having trouble. NameOfAComicBook is a mandatory parameter.

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();
}

回答1:


Noticed that attribute routing is also enabled.

routes.MapMvcAttributeRoutes();

you can also set up the route directly in the controller.

[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
    }
}


来源:https://stackoverflow.com/questions/43461825/how-to-make-a-custom-route-in-asp-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!