默认控制器路由参数

时间:2014-01-31 22:57:54

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

我需要从以下网址获取参数:https://www.mysite.com/param

下面的溃败程序可以获得参数,但其余的路径,例如mysite.com/rout1停止工作的原因很明显。

溃败会怎样处理这个?

控制器:

    public class HomeController : Controller
    {
        public ActionResult Index(string userId)
        {
            if (userId != null)
            {
                //do stuff
            }


            return View();
        }
    }

路线:

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

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

我也在使用自定义控制器工厂:

public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}

由于

2 个答案:

答案 0 :(得分:0)

变化

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

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

答案 1 :(得分:0)

这些路线应该可以解决您的问题 -

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

        routes.MapRoute(
            name: "UserId",
            url: "{UserId}",
            defaults: new { controller = "Customer", action = "Details", UserId = UrlParameter.Optional },
            constraints: new { UserId = @"[A-Za-z0-9]+" } 
        );

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

当您尝试关注

  • /123/abc/abc123 - >它将带您进入客户控制器详细信息操作
  • //Home/Index/123/Home/Index/abc/Home/Index/123abc/Home/Index/Home/Index?id=123/Home/Index?id=abc/Home/Index?id=123abc - >它将带您进入主页控制器索引操作