如何在ASP MVC中进行自定义路由 [英] How to make a custom route in ASP MVC

查看:110
本文介绍了如何在ASP MVC中进行自定义路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do something like this.

MyUrl.com/ComicBooks/{NameOfAComicBook}

我弄乱了RouteConfig.cs,但是我是一个新手,所以遇到了麻烦. 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

HomeController.cs

public ActionResult ShowComicBook(string PermaLinkName)
{


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


    return View();
}

推荐答案

忽略了也启用了属性路由.

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

这篇关于如何在ASP MVC中进行自定义路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆