Asp.net mvc 自定义MVC Url路由以显示Id和UrlSlug的混合
嗨,我要在我的博客url中使用Id和slug的混合作为url,如下所示Asp.net mvc 自定义MVC Url路由以显示Id和UrlSlug的混合,asp.net-mvc,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc Routing,嗨,我要在我的博客url中使用Id和slug的混合作为url,如下所示 http://stackoverflow.com/questions/16286556/using-httpclient-to-log-in-to-hpps-server 为此,我在我的global.asax中定义了这个Url routes.MapRoute("IdSlugRoute", "{controller}/{action}/{id}/{slug}", n
http://stackoverflow.com/questions/16286556/using-httpclient-to-log-in-to-hpps-server
为此,我在我的global.asax中定义了这个Url
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{id}/{slug}",
new {controller = "Blog", action = "Post", id = UrlParameter.Optional,slug=""});
但当我运行应用程序时,Url如下所示:
http://localhost:1245/Blog/Post?postId=dd1140ce-ae5e-4003-8090-8d9fbe253e85&slug=finally-i-could-do-solve-it
我不想要那些?和=在Url中!我只想用斜线把它们分开
请问我该怎么办
bu返回此Url的actionresult的方式如下:
public ActionResult Post(Guid postId,string slug)
{
var post = _blogRepository.GetPostById(postId);
return View("Post",post);
}
将路线更改为使用postId而不是Id
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=""});
您是否已尝试将postId和slug都设置为
UrlParameter.Optional
?
routes.MapRoute(“IdSlugRoute”,“{controller}/{action}/{postId}/{slug}”,
新的{controller=“Blog”,action=“Post”,postId=urlparmeter.Optional,slug=urlparmeter.Optional})代码>
编辑
我在当地找到了这个。我得到的是一个模型:
public class HomeViewModel
{
public Guid PostID { get; set; }
public string Slug { get; set; }
}
具有两个动作的控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
Guid guid = Guid.NewGuid();
var model = new HomeViewModel { PostID = guid, Slug = "this-is-a-test" };
return View(model);
}
public ActionResult Post(Guid postID, string slug)
{
// get the post based on postID
}
}
以及带有actionlink的视图:
@model MvcApplication1.Models.HomeViewModel
@{
ViewBag.Title = "Home Page";
}
@Html.ActionLink("Click me!", "Post", new { postId = Model.PostID, slug = Model.Slug})
要使路由正常工作,我必须硬编码路由,因为它位于默认路由之前:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("IdSlugRoute", "Home/Post/{postID}/{slug}",
new { controller = "Home", action = "Post", postID = Guid.Empty, slug = UrlParameter.Optional });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
确保自定义路线高于默认路线。它将在找到的第一条匹配路线处停止。您如何调用此路线?你能提供一个你的ActionLink等的例子吗?我刚刚编辑并添加了调用路由的actionreslust。你从ActionLink调用它,就像这样@Html.ActionLink(“foo”,“Post”,new{controller=“Blog”,postId=1,slug=“foo bar”})
@foreach(模型中的var项){@Html.ActionLink(item.Title,“Post”,“Blog”,new{postId=item.Id,slug=item.urlslaug},null)}请停止将“ASP.NET MVC”简单地称为“MVC”。一个是框架,另一个是独立于语言的设计模式。这就像把IE叫做“互联网”是的,我只是测试了一下,我得到了同样可怕的Url!