Asp.net核心自定义路由
问题描述:
我想在asp.net核心应用程序上实现自定义路由。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总是空。 关于如何向前推进的想法?
答
您的解决方案太复杂了。你可以有路径模板像
template: "{controller=Home}/{action=Index}/{seo?}"
和控制器动作就像
public ActionResult TestRoute(string seo)
{
var entity = GetEntityBySeo(seo);
return Content("");
}
够了,asp.net的MVC是足够聪明的搜索引擎优化变量绑定到从URL路径参数。