Hi ' I'm gonna to apply the mixture of Id and slug as a url in my blog url like this
http://stackoverflow.com/questions/16286556/using-httpclient-to-log-in-to-hpps-server
to do this I have defined this Url in my global.asax
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{id}/{slug}",
new {controller = "Blog", action = "Post", id = UrlParameter.Optional,slug=""});
but when I run my application Url is look like this :
http://localhost:1245/Blog/Post?postId=dd1140ce-ae5e-4003-8090-8d9fbe253e85&slug=finally-i-could-do-solve-it
I don't want to have those ? and = in Url ! I just wanna to separate them by slash how can I do about this please ??
bu the way the actionresult that returns this Url is this :
public ActionResult Post(Guid postId,string slug)
{
var post = _blogRepository.GetPostById(postId);
return View("Post",post);
}
Have you tried setting both your postId and slug to be UrlParameter.Optional?
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=UrlParameter.Optional});
EDIT
I got this to work locally. What I've got is a model:
public class HomeViewModel
{
public Guid PostID { get; set; }
public string Slug { get; set; }
}
A Controller with two actions:
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
}
}
And a View with an actionlink:
@model MvcApplication1.Models.HomeViewModel
@{
ViewBag.Title = "Home Page";
}
@Html.ActionLink("Click me!", "Post", new { postId = Model.PostID, slug = Model.Slug})
To get the routing to work I had to hard-code the route as it comes before the Default route:
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
);
}
Make sure your custom route is ABOVE the default one. It will stop at the first matching route it finds.
change your route to use postId rather than Id
routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=""});
来源:https://stackoverflow.com/questions/16286656/custome-mvc-url-rout-to-display-mixture-of-id-and-urlslug