0

嗨'我将像这样在我的博客网址中应用 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

我不想拥有那些?和 = 在网址中!我只想用斜线将它们分开我该怎么办?

bu 返回此 Url 的 actionresult 的方式是:

 public ActionResult Post(Guid postId,string slug)
        {
            var post = _blogRepository.GetPostById(postId);
            return View("Post",post);
        }
4

3 回答 3

2

确保您的自定义路线高于默认路线。它将在找到的第一条匹配路线处停止。

于 2013-04-29T20:29:52.727 回答
0

更改您的路线以使用 postId 而不是 Id

routes.MapRoute("IdSlugRoute", "{controller}/{action}/{postId}/{slug}",
                            new {controller = "Blog", action = "Post", postId = UrlParameter.Optional,slug=""});
于 2013-04-29T19:28:57.280 回答
0

您是否尝试将您的 postId 和 slug 都设置为UrlParameter.Optionalroutes.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
    }
}

还有一个带有操作链接的视图:

@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
    );

}
于 2013-04-29T19:41:04.633 回答