【问题标题】:How to have routes aliases?如何有路线别名?
【发布时间】:2016-12-29 00:01:50
【问题描述】:

我正在寻找使用 ASP.NET Core 的别名创建路由系统。

在我的数据库中,我的所有路由都有对应的别名,当用户请求服务器时,我的应用程序会查找与别名对应的路由。

现在,我想使用恢复的路由来访问正确的控制器和正确的操作。

一个例子会比长篇大论更明确(我想做的是在括号中):

用户连接到 myapp.com/hello/i/am/an/alias -> 应用程序找到对应的路由是 /MyController/Index (-> 应用程序使用 MyController 将 Index 视图发送给用户)

如果有人知道该怎么做,我接受 :D 谢谢

编辑:其实最好还是编辑一下HttpContext,但我觉得不太可能

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-1.0 asp.net-core-middleware


    【解决方案1】:

    好的,我找到答案了!!

    可以像这样在上下文中编辑路径: context.Request.Path = new PathString(newPath);

    所以我使用了始终返回 true 的 MapWhen 并使用数据库的响应编辑 context.Request.Path,而 mapHandler 只需调用 app.UseMvc:

    private void HandleMap(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    
    app.MapWhen(context => {
                string newPath = findNewPath();
    
                context.Request.Path = new PathString(newPath);
    
                return true;
            }, HandleMap);
    

    【讨论】:

      【解决方案2】:

      我想你会想在 Startup.cs 的 Configure 方法中运行类似的东西

      app.UseMvc(routes =>
      {
          routes.MapRoute(
              name: "path1",
              template: "hello/i/am/an/alias",
              defaults: {controller="MyController", action="Index"});
      
          routes.MapRoute(
              name: "path2",
              template: "i/am/another/alias",
              defaults: {controller="MyOtherController", action="Index"});
      
          // etc.
      });
      

      【讨论】:

      • 我怀疑他希望它是动态的并且来自数据库,就像 CMS 系统中使用的 slug (en.wikipedia.org/wiki/Semantic_URL#Slug) 一样,每次在运行时创建新的 slug 时都需要重建路由表,而这不是推荐
      • 是的曾,是这样的
      猜你喜欢
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多