【问题标题】:.net core custom routing with GET parameter.net 核心自定义路由与 GET 参数
【发布时间】:2018-07-25 06:54:46
【问题描述】:

.Net Core MVC,假设自定义路由如下:

App.UseMvc(routes =>
{
  routes.MapRoute(
  name: "fantasyBoardArea",
  //constraints: "{area=FantasyDraftBoard}/{controller=Test}/{league?}/{id}",
                  template: "{area=FantasyDraftBoard}/{leagueName?}/{controller=Test}/{action=Index}/{search?}");
});

有没有办法设置它,如果上面路线中的 {leagueName} 是 4 个字符串之一(NHL、NFL、NBA、MLB),那么我希望它使用典型路线 (area/ controller/action/(queryParamters),但也可以在我的控制器上使用 LeagueName 作为路由参数?我不介意路由 URL 看起来像 "domainname.com/FantasyDraftBoard/NHL/Controller/Action/"。如果它仍然隐藏“索引”就好了" 当它是索引操作时

例如:

[Area("FantasyDraftBoard")]
public class TestController : Controller
{      
    public async Task<IActionResult> Index(string leagueName, string search)
    {
       if(!String.IsNullOrEmpty(leagueName)
       {
           //do something
       }
       //Code removed, not important
    }

如果 leagueName 与这四个字符串之一不匹配,那么我希望它被忽略并被视为常规控制器/动作路由。

注意 - 忽略顶部路线中的限制,这只是为了测试和尝试。

想法?

【问题讨论】:

    标签: c# .net asp.net-core asp.net-mvc-routing mvcroutehandler


    【解决方案1】:
      app.UseMvc(routes =>
            {
                routes.MapRoute(
                            "New",
                            "{area:exists}/{leagueName?}/{controller}/{action}/{id?}",
                            new { leagueName= "NHL", controller = "Default", action = "Index" },
                            new { leagueName= "NHL|NFL" }
                        );
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
    
       [Area("FantasyDraftBoard")]
       public class DefaultController : Controller
       {
        public IActionResult Index(string leagueName)
        {
            return View();
        }
       }
    

    我验证了leagueName 设置为其中一个值。

    编辑: 如果该值不存在,则将 Leaguename 设置为 NULL,但如果它包含 4 以外的值,则返回 404

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      相关资源
      最近更新 更多