Asp.net核心自定义路由

时间:2016-05-15 10:43:28

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

我正在尝试在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);
    }
}

我的控制器actionresult:

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

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

1 个答案:

答案 0 :(得分:0)

你的解决方案太复杂了。你可以有像

这样的路线模板
template: "{controller=Home}/{action=Index}/{seo?}"

和控制器动作就像

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

这就足够了,asp.net mvc非常聪明,可以将seo变量绑定到url路径中的参数。