2009-09-06 2 views
28

여기에 약간 문제가 있습니다. 내가 작업하고있는 사이트의 각 URL 끝에 슬래시를 추가해야합니다. 그래서 같은 후행 슬래시를 가지고 사이트 내부의 모든 링크를 정의 :이 잘 작동하지만
각 URL 끝에 슬래시를 추가 하시겠습니까?

<a href="/register/">Register</a> 

여전히 하나의 작은 문제가있다 : 그것은() RedirectToAction를 호출 오는 생성 된 URL과 함께합니다. 예를 들어 :

return RedirectToAction("Register", "Users"); 

URL이 /로 변경 후행 슬래시에 등록하게됩니다. 나는 그래서 내 라우팅 시스템을 수정 :

routes.MapRoute("register", 
         "register/", 
         new {controller = "Users", action = "Register"} 
      ); 


이 아직도이 슬래쉬 것은 자동으로 추가되지 않습니다 필수!
나는이 question과이 question을 찾았지만 완전히 URL을 다시 쓰지 않는 라이브러리를 사용하고 있기 때문에 이것들은 완전히 다르다. 나는 asp.net mvc 라우팅 시스템을 사용하고있다.
그럼 녀석들이라고하니?

+0

ASP.NET Core에서이 작업을 수행하는 방법에 관심이있는 사람은'services.Configure (routeOptions => {routeOptions.AppendTrailingSlash = true;};,'services'는'IServiceCollection'입니다. – Galilyou

답변

46

이제 RouteCollection 클래스에는이 동작에 대해 true로 설정할 수있는 AppendTrailingSlash 부울이 있습니다.

+0

정말 고마워. 이것은 나를위한 최상의 해결책입니다. – Stuart

+1

대답을 올바른 것으로 표시하십시오. –

+0

아니요, MVC4에서 작동하지 않습니다. – RoninCoder

21

GetVirtualPath 메서드를 재정의하는 새 경로를 만들 수 있습니다. 이 방법에서는 후행 슬래시를 VirtualPath에 추가합니다. 이처럼 : 간결함을 위해

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) 
{ 
    VirtualPathData path = base.GetVirtualPath(requestContext, values); 

    if (path != null) 
     path.VirtualPath = path.VirtualPath + "/"; 
    return path; 
} 

내가 지금 당신이해야 할 모든 routes.MapRouteTrailingSlash() 대신 routes.MapRoute()과 경로를 등록 할 수있는 whole example on CodePaste.net

을 기록했다. GetVirtualPath()가 호출 될 때

routes.MapRouteTrailingSlash("register", 
          "register", 
          new {controller = "Users", action = "Register"} 
); 

경로는 다음 경로에 슬래시를 추가합니다. 어느 RedirectToAction() 할 것입니다.

업데이트 : CodePaste 링크가 다운 있기 때문에, 여기에 전체 코드 :

public class TrailingSlashRoute : Route { 
    public TrailingSlashRoute(string url, IRouteHandler routeHandler) 
     : base(url, routeHandler) {} 

    public TrailingSlashRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) 
     : base(url, defaults, routeHandler) {} 

    public TrailingSlashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, 
          IRouteHandler routeHandler) 
     : base(url, defaults, constraints, routeHandler) {} 

    public TrailingSlashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, 
          RouteValueDictionary dataTokens, IRouteHandler routeHandler) 
     : base(url, defaults, constraints, dataTokens, routeHandler) {} 

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { 
     VirtualPathData path = base.GetVirtualPath(requestContext, values); 

     if (path != null) 
      path.VirtualPath = path.VirtualPath + "/"; 
     return path; 
    } 
} 

public static class RouteCollectionExtensions { 
    public static void MapRouteTrailingSlash(this RouteCollection routes, string name, string url, object defaults) { 
     routes.MapRouteTrailingSlash(name, url, defaults, null); 
    } 

    public static void MapRouteTrailingSlash(this RouteCollection routes, string name, string url, object defaults, 
             object constraints) { 
     if (routes == null) 
      throw new ArgumentNullException("routes"); 

     if (url == null) 
      throw new ArgumentNullException("url"); 

     var route = new TrailingSlashRoute(url, new MvcRouteHandler()) 
        { 
         Defaults = new RouteValueDictionary(defaults), 
         Constraints = new RouteValueDictionary(constraints) 
        }; 

     if (String.IsNullOrEmpty(name)) 
      routes.Add(route); 
     else 
      routes.Add(name, route); 
    } 
} 
+0

Thanks Manticore – Galilyou

+0

CodePaste.net 깨진 링크 – John

+0

불행히도 귀하의 링크가 망가져 있습니다. (귀하의 예제 코드를 볼 수 있도록 대체 링크를 제공 할 수있는 기회는 무엇입니까?) – marcusstarnes

5

좋은 깨끗 솔루션, codingbug!

MVC3의 홈 페이지에 대해 슬래시가 두 개인 경우에만 문제가 발생했습니다.

면도기 예 :

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) 
{  
    VirtualPathData path = base.GetVirtualPath(requestContext, values);  

    if (path != null && path.VirtualPath != "")  
     path.VirtualPath = path.VirtualPath + "/";  
    return path;  
} 
3

codingbug하여 위의 솔루션은 매우 좋은 : 나는 GetVirtualPath 재정의 불통이 문제를 해결하려면
http://mysite.com//

:

@Html.ActionLink("Home", "Index", "Home") 

에 링크. 나는 매우 근사한 것을 필요로했지만, 근본적인 URL만을 위해서였다. 이 문제가있을 수 있음을 알고 있지만, 여기에 내가 한 일이 있습니다. 그것은 내 모든 환경에서 잘 작동하는 것 같습니다. 나는 그들이 처음으로 와서 훈련 슬래시가 없을 때 우리의 홈 페이지이기 때문에 그것이 또한 작동한다고 생각합니다. 그것이 내가 피하려고했던 한 사례입니다. 그것이 당신이 피하고 싶은 경우, 이것은 당신을 위해 작동합니다.

public class HomeController : Controller 
    { 
    public ActionResult Index() 
    { 
     if (!Request.RawUrl.Contains("Index") && !Request.RawUrl.EndsWith("/")) 
     return RedirectToAction("Index", "Home", new { Area = "" }); 

내가 tan을 더 필요로하는 경우. 나는 아마도 codingbug이 제공 한 코드를 사용할 것이다. 그 때까지, 나는 그것을 간단하게 유지하고 싶다.

참고 : 라우팅 엔진이 URL에서 제거 할 Home \ Index를 사용하고 있습니다.

1

나는 더 많은 upvoted 답변을 알고 있지만, 최선의 투표 응답 내 경우에는 작동하지 않았다. 나는 훨씬 쉬운 해결책을 찾았다 고 말하고 싶다.

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

모든 경우에 슬래시 "/"로 사용됩니다.

+1

아니요, 그렇지 않습니다. 이 방법을 사용하면 RouteUrl ("{name of a route"}, 새로운 RouteValueDictionary ({parameters}))을 사용하여 URL을 생성하면 후행 슬래시가 잘립니다. – Przemo

0

정말 좋은 답변이 있지만 여기에 간단한 MVC 컨트롤러 코드가 있습니다.

public ActionResult Orders() 
    { 
     if (!Request.Path.EndsWith("/")) 
     { 
      return RedirectPermanent(Request.Url.ToString() + "/"); 
     } 
     return View(); 
    } 

희망이 있으면 도움이 될 것입니다.

관련 문제