嗨'我要在我的博客网址中将Id和slug的混合物应用为网址
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的actionresult是这样的:
public ActionResult Post(Guid postId,string slug)
{
var post = _blogRepository.GetPostById(postId);
return View("Post",post);
}
答案 0 :(得分:2)
确保您的自定义路线超出默认路线。它将停在它找到的第一条匹配路线上。
答案 1 :(得分:0)
更改路线以使用postId而不是Id
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=""});
答案 2 :(得分:0)
您是否尝试将postId和slug设置为UrlParameter.Optional
?
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=UrlParameter.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
);
}