单层MVC路由

时间:2019-07-16 10:27:14

标签: asp.net-mvc-4 mvcroutehandler

我需要构建一个控制器动作来处理这种模式:

example.com/aString

其中 aString 可以是一组任意字符串中的任何一个。控制器将循环遍历每个可能的值,如果不匹配,则重定向到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();
}

如果我将“搜索”字符串硬编码到route.config中,则工作正常:

 routes.MapRoute(
       name: "search",
       url: "aString",
       defaults: new { controller = "home", action = "MatchString"}
        );

1 个答案:

答案 0 :(得分:1)

在routeconfig中

  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);
   }
 }

请记住添加所有控制器名称,因为如果您在route config中未提及它们,服务器将如何知道它是搜索参数还是Not。 希望对您有帮助