1

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

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

1 回答 1

1

在路由配置中

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

请记住添加所有控制器的名称,因为如果您没有在路由配置中提及它们,服务器如何知道它是搜索参数还是不是。希望能帮助到你

于 2019-07-16T20:54:01.947 回答