C# ASP.NET MVC中实体作为路由值的属性
我正在ASP.NETMVC5中从事一个新项目。在许多很酷的网站上,你经常看到这样的路线:C# ASP.NET MVC中实体作为路由值的属性,c#,asp.net-mvc,asp.net-mvc-5.2,C#,Asp.net Mvc,Asp.net Mvc 5.2,我正在ASP.NETMVC5中从事一个新项目。在许多很酷的网站上,你经常看到这样的路线: namespace BB.DOMAIN.Entities { public class Artist { public int Id { get; set; } public string Name { get; set; } } } routes.MapRoute( name: "Default", url:
namespace BB.DOMAIN.Entities
{
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
}
}
routes.MapRoute(
name: "Default",
url: "{controller}/{artistName}/{action}",
defaults: new { controller = "Artist", action = "Index" }
);
public ActionResult Wiki(string artistName)
{
var artist = MyContext.Artists.SingleOrDefault(x => x.Name == artistName);
//now you have the artist you want.
}
www.website.com/artist/vincent-van-gogh/wiki
www.website.com/artist/vincent-van-gogh/paints
假设我有一个实体艺术家,看起来像这样:
namespace BB.DOMAIN.Entities
{
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
}
}
routes.MapRoute(
name: "Default",
url: "{controller}/{artistName}/{action}",
defaults: new { controller = "Artist", action = "Index" }
);
public ActionResult Wiki(string artistName)
{
var artist = MyContext.Artists.SingleOrDefault(x => x.Name == artistName);
//now you have the artist you want.
}
我想通过URL中的.Name
属性查看任何给定艺术家的详细信息,如上图所示
有没有一种方法可以在ASP.NET MVC中实现这一点,而无需创建数千条独特的路由?您将有一条类似以下的路由:
namespace BB.DOMAIN.Entities
{
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
}
}
routes.MapRoute(
name: "Default",
url: "{controller}/{artistName}/{action}",
defaults: new { controller = "Artist", action = "Index" }
);
public ActionResult Wiki(string artistName)
{
var artist = MyContext.Artists.SingleOrDefault(x => x.Name == artistName);
//now you have the artist you want.
}
然后在您的ArtistController
中,您将有如下操作:
namespace BB.DOMAIN.Entities
{
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
}
}
routes.MapRoute(
name: "Default",
url: "{controller}/{artistName}/{action}",
defaults: new { controller = "Artist", action = "Index" }
);
public ActionResult Wiki(string artistName)
{
var artist = MyContext.Artists.SingleOrDefault(x => x.Name == artistName);
//now you have the artist you want.
}