2018년 11월 19일 월요일

사이트코어의 새로운 MVC Route 적용하기

이번 블로그에서는 새로운 MVC Route를 사이트코어에 적용하는 방법을 알아보자.
사이트코어의 기본 MVC Route는 "/api/sitecore/{controller}/{action}"으로써 Sitecore 9 이상의 버전에서는 Sitecore.Mvc.config, 그리고 Sitecore 9 하위 버전에서는 Sitecore.Speak.Mvc.Config 파일에서 확인할 수가 있다.
Sitecore의 자체적인 MVC Application의 컨트롤는 "/sitecore/layout/controllers" 아이템 트리에 등록되어진 Application 렌더링 아이템을 작동시키지만, 간혹 아이템의 등록없이 새로운 API를 만들어 외부 소스를 Ajax Call로 불러들여 원하는 기능을 작동시킬수가 있다.

이를 위하여, 새로운 MVC Route를 만듬으로써 기본 API 경로에 구애받지 않고 사이트코어 내에 다른 어플리케이션을 독립적으로 수행할수가 있다. 지금부터 어플리케이션을 만들고 적용시키는 방법을 알아보자.

  1. Visual Studio에서 새로운 Empty MVC 프로젝트를 만든다.

  2. App_Start 폴더에 RouteConfig.cs을 새로운 Route를 레지스터하기 위하여 수정한다.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace SitecoreSpaceNewRoute
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                //// 
                //// 기본 MVC Route
                ////
                //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                //routes.MapRoute(
                //    name: "Default",
                //    url: "{controller}/{action}/{id}",
                //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                //);
    
    
                ////
                //// 사이트코어 스페이스의 새로운 MVC Route
                ////
                routes.MapRoute(
                    name: "SitecpreSpaceRouting",
                    url: "new/sitecore/space/routing/{controller}/{action}/{id}",
                    defaults: new { controller = "SitecoreSpace", action = "MyView", id = UrlParameter.Optional }
                );
            }
        }
    }
    


  3. 새로운 폴더 "CustomRouting" 이라는 폴더를 만들고, Sitecore.Kernel assembly를 Reference에 추가하고 사이트코어의 Bin 폴더의 System.Web.Mvc를 사용하도록 프로젝트에 업데이트한다. 레지스터한 Route를 Sitecore.Pipeline의 프로세스에 적용을 시킨다.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    using System.Web.Routing;
    using Sitecore.Pipelines;
    
    namespace SitecoreSpaceNewRoute.CustomRouting
    {
        public class InitializeRoutes
        {
            /// <summary>
            /// 새로 등록한 Route는 Sitecore Pipeline에 적용시킨다.
            /// </summary>
            /// <param name="args"></param>
            public void Process(PipelineArgs args)
            {
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }
        }
    }
    


  4. 간단하게 새로운 Route의 레지스트를 마쳤으며, 이젠 Simple MVC을 만들자.

    Controller (SitecoreSpaceController.cs)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SitecoreSpaceNewRoute.Controllers
    {
        public class SitecoreSpaceController : Controller
        {
            // GET: SitecoreSpace
            public ActionResult MyView()
            {
                Models.SitecoreSpace ssnr = new Models.SitecoreSpace();
    
                // Valuable 값을 다른 소스 (예, 데이타베이스)에서 불러들일수 있지만,
                // 이번은 예제이므로, Static 값을 메뉴얼로 적용하겠다.
                ssnr.Subject = "사이트코어의 새로운 MVC Routing";
                
                ssnr.Description = "사이트코어 스페이스의 새로운 MVC Routing으로써, 기존 (Default)의 Routing 제한을 받지않고, 임의의 새로운 Route를 적용시켜 독립적인 MVC 어플리케이션을 Sitecore XP내에서 작동시킬수 있다.";
                ssnr.CurrentDateTime = DateTime.UtcNow;
    
                return View(ssnr);
            }
    
            // Redirect가 아니 다른 View rendering으로 사용할수가 있다.
            public ActionResult RedirectToBlog()
            {
                Models.SitecoreSpace ssnr = new Models.SitecoreSpace();
                ssnr.BlogUrl = "https://SitecoreSpace.Blogspot.com";
    
                return Redirect(ssnr.BlogUrl);
            }
        }
    }
    


    Model (SitecoreSpace.cs)
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    using System;
    namespace SitecoreSpaceNewRoute.Models
    {
        public class SitecoreSpace
        {
            public string FullBlogName { get; set; }
            public string BlogUrl { get; set; }
            public string Subject { get; set; }
            public string Description { get; set; }
            public DateTime CurrentDateTime { get; set; }
        }
    }
    


    View (MyView.cshtml)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    @model SitecoreSpaceNewRoute.Models.SitecoreSpace
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>MyView</title>
    </head>
    <body>
        <div class="form-horizontal">
            <h4>SitecoreSpace</h4>
            <hr />
            <div class="col-md-10">
                @Html.DisplayTextFor(model => model.Subject)
            </div>
            <br />
            <div class="col-md-10">
                @Html.DisplayTextFor(model => model.FullBlogName)
            </div>
            <br />
            <div class="col-md-10">
                @Html.DisplayTextFor(model => model.Description)
            </div>
            <br />
            <div class="col-md-10">
                링크: @Html.ActionLink("Sitecore Space Blog", "RedirectToBlog", null, new { target = "_blank" })
            </div>
            <br />
            <div class="col-md-10">
                현재시간: @Model.CurrentDateTime.ToString("yyyy-MM-dd h:mm:ss tt")
            </div>
        </div>
    </body>
    </html>
    


    View (RedirectToBlog.cshtml)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>RedirectToBlog</title>
    </head>
    <body>
        <div> 
            추가 extra 페이지
        </div>
    </body>
    </html>
    


  5. 새로운 패치파일을 만들어 사이트코어 파일시스템의 "/App_config/Include/" 폴더에 z.Sitecore.Space.Route.config을 만든다.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    <?xml version="1.0" encoding="utf-8"?>
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
      <sitecore>
        <pipelines>
          <initialize>
            <processor type="SitecoreSpaceNewRoute.CustomRouting.InitializeRoutes, SitecoreSpaceNewRoute" 
                       patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
          </initialize>
        </pipelines>
      </sitecore>
    </configuration>
    


이젠 브라우저에서 패치되어진 API 경로를 이동을 해본다.