[삶은 ASP.NET 웹 API2 방법론] (1-4) MVC Controller에서 API Controller 및 역링크

4393 단어 ASPNETWebAsp.NetApi
문제.
ASP에서 생성합니다.NET MVC Controller에서 ASP로 이동합니다.NET 웹 API controller에 대한 직접 링크 또는 역링크
 
솔루션
System을 사용할 수 있습니다.Web.Http.Routing.UrlHelp의 예를 들어 Controller에 대한 링크를 만들어서 ApiController (Url 속성으로) 를 노출시킵니다.Http RequestMessage 인스턴스는 RequestContext와 마찬가지로 첨부됩니다.이 목적을 달성하기 위해서는 링크 방법이나 루트 방법을 호출한 다음 MVC 루트의 이름과 기본 루트 (Controller 이름, Action 이름, Action 관련 매개 변수) 를 전송해야 합니다.
MVC Controller에서 System.Web.Mvc.UrlHelp, 기본 MVC 기본 Controller 클래스에 걸려 있으며 HttpRouteUrl을 통해 웹 API 링크를 생성할 수 있습니다
작업 원리
ASP를 사용하는 경우NET 웹 API가 기존 MVC 응용 프로그램의 일부일 때 흔히 볼 수 있는 요구 사항은 두 종류의 Controller 간에 서로 연결할 수 있다는 것이다.웹 API에서 MVC Controller에 대한 링크를 만들 때 실제로 사용하는 방법과 두 개의 웹 API Controller 사이의 링크를 만드는 방법은 UrlHelper의 링크나 루트와 완전히 같다.링크와 라우팅으로 생성된 링크는 다소 다릅니다.
  • 링크 방법은 절대 링크를 생성할 것이다
  • 루트 방법은 상대적인 링크를 생성한다.

  • 반대로, 우리가 MVC에서 웹 API로 연결했을 때, Http Route Url은 ASP가 아니었다.NET 웹 API 프로그램 집합의 확장 방법은 Url Helper 클래스의 구성원입니다. System에서.Web.Mvc에서.이 Helper는 httproute라는 개인적인 상수를 사용했는데 Http Route Url을 사용할 때마다 Route Value Dictionray에 추가됩니다.
     
    우리는 3-12에 엔진 생성이 루트 뒤에 연결된 이야기를 깊이 있게 배우고 이해할 것이다.
     
    코드 데모
    책에 대한 간단한 웹 응용 프로그램을 가정하십시오.명세서 1-10과 같이 간단한 Book 모델은 메모리를 사용하고 API/MVC 라우트를 구성합니다.이 예의 목적은 웹 API와 MVC 컨트롤러 사이에서 같은 모델을 완벽하게 사용하는 것이다.이 목록에 있는 위조 데이터를 사용하여 웹 API와 MVC 사이에 서로 연결된 상황을 설명할 것입니다.
     
    명세서 1-10.모델 사례, 라우팅 및 메모리 스토리지
    public class Book {
         public int Id { get; set; }
         public string Author { get; set; }
         public string Title { get; set; }
         public string Link { get; set; }
     }
     
     public static class Books {
         public static List List = new List     {
             new Book {Id = 1, Author = "John Robb", Title = "Punk Rock: An Oral History"},
             new Book         {
                 Id = 2,
                 Author = "Daniel Mohl",
                 Title = "Building Web, Cloud, and Mobile Solutions with F#"         },
             new Book         {
                 Id = 3,
                 Author = "Steve Clarke",
                 Title = "100 Things Blue Jays Fans Should Know & Do Before They Die"         },
             new Book         {
                 Id = 4,
                 Author = "Mark Frank",
                 Title = "Cuban Revelations: Behind the Scenes in Havana "         }
         };
     }
     
         public class RouteConfig     {
             public static void RegisterRoutes(RouteCollection routes)
             {
                 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                 routes.MapRoute(
                     name: "BookPage",
                     url: "books/details/{id}",
                     defaults: new {controller = "BooksPage", action = "Details"}
                     );
             }
         }
     
         public static class WebApiConfig     {
             public static void Register(HttpConfiguration config)
             {
                 config.Routes.MapHttpRoute(
                     name: "DefaultApi",
                     routeTemplate: "api/{controller}/{id}",
                     defaults: new {id = RouteParameter.Optional}
                     );
             }
         }

     
    명세서 1-11에서 보듯이 이 코드는 웹 API에서 MVC Controller로의 링크를 만들기 위한 것입니다.BooksPageController는 책 처리를 담당합니다.링크를 생성하기 위해 UrlHelper의 링크 방법을 호출한 다음 관련 루트의 값을 전달할 수 있습니다.
     
    명세서 1-11 ASP.NET 웹 API ApiController를 MVC Controller에 연결
    public class BooksController : ApiController{
        public Book GetById(int id)
        {
            var book = Books.List.FirstOrDefault(x => x.Id == id);
            if (book == null) throw new HttpResponseException(HttpStatusCode.NotFound);
            book.Link = Url.Link("BookPage", new {controller = "BooksPage", action = "Details", id});
            return book;
        }

     
    목록 1-12와 같이 반대 방향의 링크로, MVC Controller에서 ApiController로 이동합니다.이런 상황에서 MVC의 특정한 방법인 UrlHelper를 사용하면 HttpRouteUrl에서 확장하는 방법입니다.
     
    명세서 1-12.MVC Controller에서 ASP로 링크.NET Web API
    public class BooksPageController : Controller{
        public ActionResult Details(int id)
        {
            var book = Books.List.FirstOrDefault(x => x.Id == id);
            if (book == null) return new HttpNotFoundResult();
            book.Link = Url.HttpRouteUrl("DefaultApi", new {controller = "Books", id});
            return View(book);
        }
    }

     
     
     

    좋은 웹페이지 즐겨찾기