单层 MVC 路由
MVC route with single level
我需要构建一个控制器操作来处理这种模式:
示例。com/aString
其中 aString 可以是一组任意字符串中的任何一个。控制器将循环遍历每个可能的值,如果 none 匹配,则重定向到 404.
我认为这只是重新编码包罗万象的问题,但到目前为止我还是一片空白。目前正在使用 Sherviniv 的建议:
//Catchall affiliate shortcuts.
routes.MapRoute(
name: "affLanding",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
控制器:
public ActionResult MatchString(string query)
{
_logger.Info("affLanding: " + query);
return View();
}
如果我将我的 'search' 字符串硬编码到 route.config 中,事情就会起作用:
routes.MapRoute(
name: "search",
url: "aString",
defaults: new { controller = "home", action = "MatchString"}
);
在路由配置中
routes.MapRoute(
name: "Controller1",
url: "Controller1/{action}/{id}",
defaults: new { controller = "Controller1", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Controller2",
url: "Controller2/{action}/{id}",
defaults: new { controller = "Controller2", action = "Index", id = UrlParameter.Optional }
);
//Other controllers
routes.MapRoute(
name: "search",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
routes.MapRoute(
name: "Default",
url: "",
defaults: new
{
controller = "Home",
action = "Index"
}
);
在你的控制器中
public ActionResult Index()
{
reutrn view();
}
public ActionResult MatchString(string query)
{
if(Your Condition)
{
//when string query doesnt find
throw new HttpException(404, "Some description");
}
else
{
return view(Your model);
}
}
请记住添加所有控制器的名称,因为如果您不在路由配置中提及它们,服务器将如何知道它是否是搜索参数。
希望对你有帮助
我需要构建一个控制器操作来处理这种模式:
示例。com/aString
其中 aString 可以是一组任意字符串中的任何一个。控制器将循环遍历每个可能的值,如果 none 匹配,则重定向到 404.
我认为这只是重新编码包罗万象的问题,但到目前为止我还是一片空白。目前正在使用 Sherviniv 的建议:
//Catchall affiliate shortcuts.
routes.MapRoute(
name: "affLanding",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
控制器:
public ActionResult MatchString(string query)
{
_logger.Info("affLanding: " + query);
return View();
}
如果我将我的 'search' 字符串硬编码到 route.config 中,事情就会起作用:
routes.MapRoute(
name: "search",
url: "aString",
defaults: new { controller = "home", action = "MatchString"}
);
在路由配置中
routes.MapRoute(
name: "Controller1",
url: "Controller1/{action}/{id}",
defaults: new { controller = "Controller1", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Controller2",
url: "Controller2/{action}/{id}",
defaults: new { controller = "Controller2", action = "Index", id = UrlParameter.Optional }
);
//Other controllers
routes.MapRoute(
name: "search",
url: "{query}",
defaults: new
{
controller = "Home",
action = "MatchString"
}
);
routes.MapRoute(
name: "Default",
url: "",
defaults: new
{
controller = "Home",
action = "Index"
}
);
在你的控制器中
public ActionResult Index()
{
reutrn view();
}
public ActionResult MatchString(string query)
{
if(Your Condition)
{
//when string query doesnt find
throw new HttpException(404, "Some description");
}
else
{
return view(Your model);
}
}
请记住添加所有控制器的名称,因为如果您不在路由配置中提及它们,服务器将如何知道它是否是搜索参数。 希望对你有帮助