[ASP.NET] MVC4 사용자 정의 Route 만들기

사용자 정의 Route 만들기

이번 포스팅은 ASP.net의 공식 MVC 관련 자습서인 http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs 의 글을 참고해서 작성했습니다. 보다 자세한 내용은 해당 링크를 참고해주세요.

ASP.NET MVC에서는 기본적으로 {controller}/{action}/{id}라는 Route를 제공한다.
하지만 이 외에도 다양한 규칙을 사용자가 정의하여 사용하고 싶을 때 사용자 정의 Route를 만들어 활용할 수 있다.

예들 들어 검색 페이지의 경우,

http://localhost/Search/SearchType/Keyword/Page의 형태로 URL을 구성하려고 한다.
이 때 Global.asax 파일을 수정해 간단히 사용자 정의 Route를 만들 수 있다.

1. Globa.asax 파일 수정

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WinTalk
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                name: "Search",                              //라우트 이름
                url: "Search/{SearchType}/{Keyword}/{Page}", //지정하고자 하는 URL 형태
                defaults: new                                //매개변수 기본값
                {
                    controller = "Search",
                    action = "Index",
                    SearchType = "All",
                    Keyword = "Keyword",
                    Page = 1
                },
                constraints: new                                //매개변수 제약조건
                {
                    Page = @"(\d)+"
                }

 );

 }
 protected void Application_Start()
 {
 RegisterRoutes(RouteTable.Routes);

 AreaRegistration.RegisterAllAreas();

 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
 }
}

2. SearchContoller.cs 수정

using System.Web.Mvc;

namespace WinTalk.Controllers
{
    public class SearchController : Controller
    {
        //
        // GET: /Search/

        public string Index(string SearchType, string Keyword, int Page)
        {
            return "매개변수 출력<br />SearchType: " + SearchType + "<br />Keyword: " + Keyword + "<br />Page: " + Page.ToString();
        }

    }
}

위와 같이 파일을 설정 한 뒤 http://localhost/Search로 접속해보면 아래와 같은 결과를 확인할 수 있다.

매개변수 출력
SearchType: All
Keyword: Keyword
Page: 1

위 코드를 활용해서 다양한 Route Rule을 정의할 수 있다!

한가지 주의할 점이 있다면, Route 정의 코드가 위쪽에 있을수록 우선 순위를 가진다는 것이다.
예를 들어 위 예제에서 사용자 정의 Route가 기본 Route(/{controller}/{action}/{id}) 보다 하단에 위치한다면 http://localhost/Search/SearchType/Keyword 이라는 주소로 접근 했을 때 우리가 원하는 결과가 아닌 기본 Route의 룰이 적용된다.

댓글

이 블로그의 인기 게시물

[IIS] OraOLEDB.Oracle.1 설치 방법

[IIS] IIS 7.5 HTTP 오류 401.3 - Unauthorized 해결방법

[ASP] Server.CreateObject를 호출하지 못했습니다. 이 개체에 액세스할 수 없습니다.