1

질문 :MVC URL 라우팅, 잘못된 경로로 라우팅, 이유는 무엇입니까?

이 내 RegisterRoutes입니다 :

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 


      routes.Add("ImagesRoute", new Route("graphics/{*filename}", new HttpRuntime.Routing.ImageRouteHandler())); 


      // insert_dateti 
      routes.MapRoute(
       "Default", // Routenname 
       "{controller}/{action}/{id}", // URL mit Parametern 
       new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameterstandardwerte 
       //new { controller = "Home", action = "Splash", id = UrlParameter.Optional } // Parameterstandardwerte 
       //new { controller = "Folders", action = "Content", id = UrlParameter.Optional } // Parameterstandardwerte 
      ); 



     } // End Sub RegisterRoutes 

을 그리고 이것은 내 경로 처리기

using System; 
using System.IO; 
using System.Web; 
using System.Linq; 
using System.Web.UI; 
using System.Web.Routing; 
using System.Web.Compilation; 
using System.Collections.Generic; 


namespace HttpRuntime.Routing 
{ 


    public class ImageRouteHandler : IRouteHandler 
    { 


     public string MapRemoteLocation(string strPath) 
     { 
      if (string.IsNullOrEmpty(strPath)) 
       return ""; 

      string strBaseURL = "http://madskristensen.net/themes/standard/"; 
      return strBaseURL + strPath; 
     } 

     public IHttpHandler GetHttpHandler(RequestContext requestContext) 
     { 


      string filename = requestContext.RouteData.Values["filename"] as string; 

      if (string.IsNullOrEmpty(filename)) 
      { 
       // return a 404 HttpHandler here 
       requestContext.HttpContext.Response.StatusCode = 404; 
       requestContext.HttpContext.Response.End(); 
       return null; 
      } // End if (string.IsNullOrEmpty(filename)) 
      else 
      { 
       requestContext.HttpContext.Response.Clear(); 
       requestContext.HttpContext.Response.ContentType = GetContentType(filename); 
       requestContext.HttpContext.Response.Redirect(MapRemoteLocation(filename)); 


       // find physical path to image here. 
       //string filepath = requestContext.HttpContext.Server.MapPath("~/test.jpg"); 


       // string stPath = requestContext.HttpContext.Request.Url.AbsolutePath; 
       //requestContext.HttpContext.Response.WriteFile(filepath); 
       //requestContext.HttpContext.Response.End(); 
      } // End Else of if (string.IsNullOrEmpty(filename)) 

      return null; 
     } // End Function GetHttpHandler 


     public static void MsgBox(object obj) 
     { 
      if (obj != null) 
       System.Windows.Forms.MessageBox.Show(obj.ToString()); 
      else 
       System.Windows.Forms.MessageBox.Show("obj is NULL"); 
     } // End Sub MsgBox 


     private static string GetContentType(String path) 
     { 
      switch (Path.GetExtension(path)) 
      { 
       case ".bmp": return "Image/bmp"; 
       case ".gif": return "Image/gif"; 
       case ".jpg": return "Image/jpeg"; 
       case ".png": return "Image/png"; 
       default: break; 
      } // End switch (Path.GetExtension(path)) 
      return ""; 
     } // End Function GetContentType 


    } // End Class ImageRouteHandler : IRouteHandler 


} // End Namespace HttpRuntime.Routing 

이의 목표입니다 난/홈/색인이있을 때. cshtml

<img src="graphics/mads2011.png?v=123" title="Compose E-Mail" alt="Compose E-Mail" /> 

원격 호스트에서 그림을 다운로드합니다.

내가

routes.Add("ImagesRoute", new Route("graphics/{filename}", new HttpRuntime.Routing.ImageRouteHandler())); 

을하지만 하위 폴더를 허용하기 위해

routes.Add("ImagesRoute", new Route("graphics/{*filename}", new HttpRuntime.Routing.ImageRouteHandler())); 

로 변경할 때, 다음 그래픽 /에 대한 모든 URL 동작을 리디렉션으로 잘 한 작동합니다.

나는 홈/Index.cshtml에

$(function() { 
     $("#divJsTreeDemo").jstree({ 
     "json_data" : { 
      "ajax" : { 
       "url": "@Url.Action("GetNodesJson", "Home")" 
       //"url": "@Url.Action("GetTreeData", "Home")" 
       ,"async" : true 

이있을 때

결과 HTML 페이지에서 AJAX 호출에 대한 URL은

"url": "/graphics?action=GetNodesJson&amp;controller=Home" 

왜이

이됩니까? 어떻게 해결할 수 있습니까? ImagesRoute를 아래쪽으로 이동하면 JavaScript 경로가 올바르게 전달되지만 컨트롤러 "그래픽"으로 라우팅되기 때문에 더 이상 원격 이미지를 얻을 수 없으며 예외가 없습니다.

+1

을 나는 절대적으로 라우팅 싫어 ... 다음과 같이

은 기본 경로를 변경

. 나는 너의 고통을 느낀다. 미안 내가 도와 줄 수 없어. – Jamiec

+0

아, 라우팅 문제가있을 때 http://mvccontrib.codeplex.com/에서 경로 디버거를 사용하는 것이 도움이 될 수 있습니다. – Jamiec

답변

2

ImagesRoute 을 사용하면 경로에서 링크를 구축 할 때 경로 테이블의 Default 경로보다 선행하면 링크가 항상 링크를 작성하는 데 사용됩니다. 그러나 요청을 처리 할 때 ImagesRoute 경로는 요청 시작으로 만 충족되기 때문에 예상대로 작동합니다. http://mysite.com/graphics/...

이 문제를 해결하려면 ImagesRoutes를 기본 경로 아래로 이동해야합니다. 기본 경로에 RouteConstraint을 입력하면 graphics으로 시작하는 모든 요청이 기본 경로로 실패합니다. 나는 절대적으로 aspnetmvc 사랑

routes.MapRoute(
    "Default", // Routenname 
    "{controller}/{action}/{id}", // URL mit Parametern 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // defaults 
    new { controller = @"^(?!graphics).+" } // constraint 
); 
+0

위대한 작품! 고마워요! 나는 왜 아직도/Home/GetNodesJson이/graphics/무엇이든간에 @ Url.Action ("GetNodesJson", "Home") "이 왜 그런지 이해하지 못한다고 말하지만, 왜 @ Url.Action ("ActionName "," ControllerName ") 그래픽/컨트롤러 이름/ActionName으로 변합니다. 어쨌든, 그것은 그냥 route2로 확장 된 route2 채 웁니다 ... 그 부분을 라우팅 이해하기 위해 MVC 원본을 읽어야 할 것 같아요. –

+0

ImagesRoute URL 매개 변수는 단일 욕심 많은 일치로 구성되며 MVC에서 빌드 할 모든 링크와 일치합니다.링크 건물 측면에서는 모든 것이 해당 경로와 일치합니다. 답변을 표시하십시오. 감사. – counsellorben