由于我为控制器的特定操作编写了路径,我是否需要为Controller内的所有操作编写路由?

时间:2016-03-04 17:15:49

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

我正在为我的MVC应用程序写几条路线。我的应用程序有以下路径:

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

当我想访问默认值时使用上面的路线,如:

www.servicili.com/budget/edit/1

www.servicili.com/professional/view/234

但是,我为特定目的创建了以下路线:

routes.MapRoute(
                name: "Perfil",
                url: "{UsuApelido}",
                defaults: new { controller = "Perfil", action = "Index"}
            );

上面的路由,用于访问“管道工”的URL配置文件,例如: 的 www.servicili.com/MarkZuckberg

配置文件详细信息位于控制器 Perfil 和操作索引,但是,因为我写了这条路线,所有其他操作都无法正常工作。

例如:如果我尝试访问其他控制器中的索引操作,则会重定向到 Perfil 索引

- 问题是:由于我为控制器的特定动作编写了路径,我是否需要为Controller内的所有动作编写路径?

1 个答案:

答案 0 :(得分:2)

To solve your problem try like this,

First define constraint,

public class PlumberUrlConstraint: IRouteConstraint
{
   public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
   {
      var db = new YourDbContext();
      if (values[parameterName] != null)
      {
        var UsuApelido = values[parameterName].ToString();
        return db.Plumbers.Any(p => p.Name == UsuApelido);
      }
      return false;
   }
}

Define two routes, put "Default" route at 2nd position

routes.MapRoute(
            name: "Perfil",
            url: "{*UsuApelido}",
            defaults: new { controller = "Perfil", action = "Index"},
            constraints: new { UsuApelido = new PlumberUrlConstraint() }
        );

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

Now if you have an 'Index' action in 'Perfil' Controller, you can get plumber name like this,

public ActionResult Index(string UsuApelido)
{
  //load the content from db with UsuApelido
  //display the content with view
}

Hope this help.