【问题标题】:Asp.net core Custom routingAsp.net core 自定义路由
【发布时间】:2016-05-15 10:43:27
【问题描述】:

我正在尝试在 asp.net 核心应用程序上实现自定义路由。

想要的结果如下:

http://Site_URL/MyController/Action/{Entity_SEO_Name}/

Entity_SEO_Name 参数将是保存到数据库中的唯一值,它将帮助我识别我要显示的实体的 ID。

为了实现这一点,我实现了一个自定义路由:

routes.MapMyCustomRoute(
            name: "DoctorDetails",
            template: "       {controller=MyController}/{action=TestRoute}/{name?}");


 public class MyTemplateRoute : TemplateRoute
 {
     public override async Task RouteAsync(RouteContext context)
    {
        //context.RouteData.Values are always empty. Here is the problem.
        var seo_name = context.RouteData.Values["Entity_SEO_Name"];

        int entityId = 0;
        if (seo_name != null)
        {
            entityId = GetEntityIdFromDB(seo_name);
        }
        //Here i need to have the id and pass it to controller
        context.RouteData.Values["id"] = entityId;
        await base.RouteAsync(context);
    }
}

我的控制器操作结果:

  public ActionResult TestRoute(int id)
  {
       var entity = GetEntityById(id);
            return Content("");
  }

这种方法的问题是 context.RouteData.Values 总是空的。 关于如何推进这一计划的任何想法?

【问题讨论】:

    标签: asp.net-core asp.net-routing asp.net-core-1.0


    【解决方案1】:

    您的解决方案太复杂了。您可以拥有类似的路线模板

    template: "{controller=Home}/{action=Index}/{seo?}"
    

    和控制器动作一样

    public ActionResult TestRoute(string seo)
    {
        var entity = GetEntityBySeo(seo);
        return Content("");
    }
    

    够了,asp.net mvc很聪明,可以将seo变量绑定到url路径的参数上。

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2020-04-15
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多