我需要从以下网址获取参数: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;
}
}
由于
答案 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
- >它将带您进入主页控制器索引操作