ASP.NET 기초 강의실

시삽: 레드플러스 님 
게시판 이동:
 제목 : ASP.NET URL 라우팅: http://url.com/ID를 http://url.com/U.aspx?id=ID로 이동시키기
글번호: 352
작성자: 레드플러스
작성일: 2014/10/07 오전 5:20:00
조회수: 8801
파일: 20141007_WebUrlRouting_ASP.NET URL 라우팅.zip (8.00 MB) / 전송수: 1098

요약

ASP.NET URL 라우팅:

http://www.url.com/ID => http://www.url.com/Default.aspx?ID=ID

 http://www.url.com/abc => http://www.url.com/Default.aspx?ID=abc
 http://www.url.com/cba => http://www.url.com/Default.aspx?ID=cba

해결책: One ASP.NET(Web Forms & MVC)

 

소개

사이트를 운영함에 있어서, 사용자 ID 또는 특정값을 URL로 요청하여 그에 해당하는 추가적인 리디렉션 등이 필요한 경우가 있는데,

http://url.com/CommunityName 요청시 http://url.com/Default.aspx?name=CommunityName 식으로 이동해야하는 기능을 구현시 본 아티클이 도움이 된다.

 

따라하기

(1) Visual Studio 2013을 사용하여 One ASP.NET(Web Forms & MVC) 웹 프로젝트 생성

 

(2) App_Start/RouteConfig.cs에 라우팅 추가

using System.Web.Mvc;
using System.Web.Routing;

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

            // 웹 사이트 루트의 라우트 경로는 무시
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

            // 라우트 경로 추가
            routes.MapRoute(
                name: "GoRedirect",
                url: "{community}",
                defaults: new { controller = "Go", action = "Index" }
            );

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

 

 

(3)(1) Controllers/GoController.cs 파일 생성 및 Index 액션 메서드 변경

using System.Web.Mvc;

namespace WebUrlRouting.Controllers
{
    public class GoController : Controller
    {
        // GET: Go
        public ActionResult Index(string community)
        {
            // 세션변수를 사용하여 사용자별 특정 기능 수행
            Session["Community"] = community; 

            // 특정 페이지로 이동
            return Redirect("~/Default.aspx?community=" + community);
        }
    }
}

 

(3)(2) 만약, 특정 문자열 값에 해당하는 자료만을 기준으로 URL 라우팅 기능을 구현하고자 한다면, 아래 코드와 같이 Go 컨트롤러의 Index 액션 메서드에 필터링 코드를 추가하면 된다.

        public ActionResult Index(string community)
        {
            // Communities 테이블에서 넘겨온 community 변수의 값이 CommunityName 필드에 있는지 확인 있으면 해당 값으로 출력/이동시키고, 그렇지 않으면 FileNotFound 기능 구현
            string[] communities = { "데브렉", "GOT7", "2PM", "2AM" };
            // 배열 또는 데이터베이스에 들어있지 않은 커뮤니티명이 넘겨온다면, 404 에러 출력
            if (!communities.Contains(community, StringComparer.OrdinalIgnoreCase))
            {
                return new HttpNotFoundResult(); 
            }


            // 세션변수를 사용하여 사용자별 특정 기능 수행
            Session["COMMUNITY"] = community;

            // 특정 페이지로 이동: 해당 페이지로 이동 후 community 변수에 해당하는 내용만 보이기 기능 구현
            return Redirect("~/MainPage.aspx?Community=" + community);
        }

 

 

(4) 웹 브라우저에서 테스트

~/2PM => ~/Default.aspx?community=2PM 식으로 이동됨을 확인

 

마무리

추가적으로 현재 로직을 잘 응용하면,

tinyurl.com, bit.ly과 같은 Shorten URL 기능을 구현할 수 있다.

url.com/A1C2a => http://www.dotnetkorea.com/ 식으로 이동할 수 있게 가능

 

끝.

 

 
이전 글   다음 글 삭제 수정 답변 글쓰기 리스트


관련 아티클 리스트
  제       목 파일 작성자 작성일 조회
이전글 MIRACLE Pattern(패턴)에 의한 웹 프로젝트 구조 만들기 - 레드플러스 2014-10-09 2552
현재글 ASP.NET URL 라우팅: http://url.com/ID를 http://url.... 20141007_WebUrlRouting_ASP.NET URL 라우팅.zip(8.00 MB) 레드플러스 2014-10-07 8801
다음글 전역 리소스(App_GlobalResources)를 사용한 다국어 처리 관련 코드 조... - 레드플러스 2014-10-02 3044
 
손님 사용자 Anonymous (손님)
로그인 Home