如何自定义MVC url路径

时间:2014-01-31 18:06:23

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

我正在尝试创建一个到MVC控制器的干净URL路径,我需要一点帮助。

示例所需路径:http://www.linkedin.com/in/alumcloud。此路径来自LinkedIn,并注意它是如何拥有/in/alumcloud

我希望我的阅读:http://www.alumcloud.com/alumcloud/somecompanyname

我如何使用MVC控制器执行此操作?

下面是我的MVC控制器中唯一的代码,因为这个控制器只需要响应GET HTTP方法。

public class AlumCloudController : AlumCloudMvcControllerBase
{
    // GET: /AlumCloud/Details/5
    public ActionResult Details(string companyName)
    {
        return View();
    }
}

- 这是我的RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

-----------------------------------第二次尝试------- -----------------------------

- 路线代码2

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

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

            routes.MapRoute(
                name: "Public",
                url: "ac/{companyName}",
                defaults: new { controller = "AlumCloudController", action = "UserProfile" }
            );
 }

- 控制器代码2

public class AlumCloudController : AlumCloudMvcControllerBase
{
    // GET: /AlumCloud/Details/5
    public ActionResult UserProfile(string companyName)
    {
        return View();
    }
}

- 网址

'/ac/' + options.person.CompanyName 

- 快照404错误

404 mvc error

1 个答案:

答案 0 :(得分:2)

尝试添加此路线以上您的默认路线:

routes.MapRoute(
    name: "Profile",
    url: "alumcloud/{companyName}",
    defaults: new { controller = "AlumCloudController", action = "Details" }
);