0

이 두 경로가 있습니다. 두 번째 매개 변수는 선택적 사용자 지정 변수를 작업 메서드에 전달하고이 메서드를 DatedPosts라는 작업에 연결합니다.원하는 작업으로 라우팅하지 못하고 사용자 지정 세그먼트 변수를 전달하지 않음

routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 


    routes.MapRoute(
    name: "GetDatePosts", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "DatedPosts", id = UrlParameter.Optional} 
    ); 

내 동작 메서드는 정의되어 있고 날짜가되면 매개 변수를 가져오고 블로그에서 모든 게시물을 가져옵니다. 즉, 내가 그 시각에 지나가는 날짜가 있다면. 이 방법은 내가 그것을 수행 할 작업을 수행합니다

 public ActionResult DatedPosts(string id) 
     { 
      //Post post = new Post(); 

      m_requestedDatedPosts = true; 
      Session["RequestDatedPosts"] = m_requestedDatedPosts; 

      string date = null; 

      char oldChar = '/'; 
      char newChar = '-'; 
      if (!string.IsNullOrEmpty(id)) 
      { 
       date = id.ToString(); 
      } 

      //will hold the formated date 
      string formatedDate = null; 


      if (!string.IsNullOrEmpty(date)) 
      { 
       //Convert dateString to shortDateString by replacing slashes with dashes 
       formatedDate = date.Replace(oldChar, newChar); 
      } 
      else 
      { 
       ViewBag.CustomVariable = id == null ? "no posts with that date" : id; 
       return RedirectToAction("Error", "Posts"); 
      } 

      //put all posts in a list 
      List<Post> m_posts = (from post in db.Posts select post).ToList(); 

      List<Post> m_datedPosts = new List<Post>(); 

      //var posts = (from post in db.Posts where post.CreatedDate == DateTime.Parse(formatedDate) select post).ToList(); 

      //Traverse the list of posts and get those with the given date 
      foreach (var post in m_posts) 
      { 
       if (post.CreatedDate.ToShortDateString() == formatedDate) 
       { 
        m_datedPosts.Add(post); 
       } 
      } 

      //If there are no posts with that date redirect to Error action on post controller 
      if (m_datedPosts.Count() == 0) 
      { 
       return RedirectToAction("Error", "Posts"); 
      } 

      Session["DatedPostList"] = m_datedPosts.ToList(); 

      return RedirectToAction("Index", "Posts"); 
     } 

This is my action View : 

@{ 

    List<Post> posts; 


    if (Session["RequestDatedPosts"] == null) 
    { 

     string requestDatedPostsStr = Session["RequestDatedPosts"].ToString(); 

     requestDatedPosts = Convert.ToBoolean(requestDatedPostsStr); 

    } 


    var datedPostList = (List<Post>)Session["DatedPostList"]; 

     if (requestDatedPosts) 
    { 

     posts = datedPostList; 
    } 

} 

foreach (var post in posts) 
{ 


    <div class="newsResult"> 

     <div class="title">@Html.DisplayFor(modelItem => post.Title)</div> 

     <div class="updated"> <b>Created:</b> @Html.DisplayFor(modelItem => post.CreatedDate) </div> 

     <div class="updated"> <b>Updated:</b> @Html.DisplayFor(modelItem => post.UpdateDate)</div> 

     <div class="data"> <b></b> @Html.DisplayFor(modelItem => post.Body)</div> 

} 

결과는 라우팅 경우에만, 나는 사전에이 같은 경로에서 날짜를 정의하고 만 것은이 경로가 작품이다 :

routes.MapRoute(
    name: "GetDatePosts", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "DatedPosts", id = "2014/05/21" } 
    ); 

그러나 이것은 내가 원하는 것이 아닙니다. 브라우저에서이 Localhost/DatedPosts/2014/05/21 /과 같이 원하는 날짜를 입력하고 해당 날짜에 게시물이있는 경우 해당 게시물을 가져오고 싶습니다.

나는 모두 HTTP 오류 404.0을 찾을 수 없습니다. 또한 테스트를하면서 피하고 싶은 또 다른 것을 발견했습니다. 내 라우팅 작동 방식은 LocalHost/DatedPosts/DatedPosts/링크를 작성해야 적어도 오류 페이지로 리다이렉트된다는 것입니다. 다시 말하지만, 이것이 내가 원하는 바가 아니기 때문에 Localhost/DatedPost/2014/05/22와 같은 링크를 원하고 그 날짜에 모든 게시물을 얻으려고합니다.

아무도 도와 줄 수 있습니까?

미리 감사드립니다.

답변

1

나열된 경로는 기본적으로 동일하며 URL 부분은 동일하므로 라우팅 엔진은 요청을 구분할 수 없습니다.

은 후 다음과 같은 시도하는 것을 얻을 :

routes.MapRoute(
    name: "GetDatePosts", 
    url: "DatedPost/{*id}", 
    defaults: new { controller = "Home", action = "DatedPosts", id = UrlParameter.Optional} 
); 

// default route should (generally) be last to ensure it doesn't catch any requests that may look similar 
routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 
+0

고맙습니다 브렌트을! 나는 그것이 효과가 있다고 생각한다. 나는 첫 번째 경로에 "PostsAt/{* id}"라고 정의 된 URL이있다.이 URL은 "PostsAt/{* catchall}"과 같은가? 적어도 세 개가있는 경우 왜 두 세그먼트 만 있습니까? – bluetxxth

+1

예, 아니요,'*'는 catch all을 기부하고, URL의'id' 부분은 액션의'string id' 매개 변수에 매핑합니다. 액션의 매개 변수가'string date' 인 경우, URL은'PostsAt/{* date}'로 정의 될 수 있습니다. catch를 모두 사용하지 않았다면, 날짜 부분은'PostsAt/{year}/{month}/{day}'로 정의되어야합니다. 이는'string year, string month, string day '를 매개 변수로 사용합니다. –