티스토리 뷰

반응형

이전 포스트에서 DAL 프로젝트 설정에 대해서 알아 보았다. 이제 Web 프로젝트에 WebAPI를 OData Endpoint로 구현하는 방법에 대해서 알아보자

 

1. PCLSample.Web

Silverlight와 WCF DataService를 호스팅하는 프로젝트

.Net Framework 4.5, MVC4, WebAPI 

 

Nuget packages

너무 많아서 모두 적을 수 없고, 핵심되는 몇개만 기술

PortableIoC

Microsoft.AspNet.WebApi.OData

Microsoft.Data.OData

System.Spatial

 

Create a Read-Only OData Endpoint with ASP.NET Web API

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/getting-started-with-odata-in-web-api/create-a-read-only-odata-endpoint

 

위의 포스트에 있는 내용을 기준으로 생각하면되고, Nuget package 중 PortableIoC는 Nuget에서 검색해서 설치하고, 나머지는 Nuget Console 모드에서 Install-Package Microsoft.AspNet.WebApi.OData를 입력해서 설치하면된다.

 

1-1. GlobalVariables

웹 전체에서 사용할 클래스로 IoC Container를 가지고 있다.

 

    /// <summary>
    /// 전체 공용
    /// </summary>
    public static class GlobalVariables
    {
        private static IPortableIoC _container;
        /// <summary>
        /// PortableIoC Conatiner
        /// </summary>
        public static IPortableIoC Container
        {
            get { return _container = _container ?? new PortableIoc(); }
            private set { _container = value; }
        }
    }

 

 

1-2. Glabal.asax.cs

웹이 시작하면서 컨테이너에 인터페이스들을 등록한다.

 

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

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

 

            //Regiser user interface
            GlobalVariables.Container.Register<IUnitOfWork>(ioc => new UnitOfWork());

            //db init
            System.Data.Entity.Database.SetInitializer(new PCLSampleContextInitializer());

        }
    }

 

1-3. WebApiConfig

WebApi설정 클래스로 기존에 있던 내용을 모두 주석처리하고 아래 내용으로 변경한다.

 

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<PersonModel>("People");

 

            Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
            config.Routes.MapODataRoute("ODataRoute", "odata", model);

 

            config.EnableQuerySupport();
        }
    }

 

1-4. PeopleController

WebAPI OData Endpoint controller로 구성방법에 대해서는

 

Supporting OData CRUD Operations in ASP.NET Web API

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-crud-operations

포스트를 참고한다.

 

실제 CRUD를 모두 테스트를 해보지 않아서 차후에 수정이 될 것이라 생각한다.

 

    public class PeopleController : EntitySetController<PersonModel, int>
    {
        private IUnitOfWork _uow;

        public PeopleController()
        {
            _uow = GlobalVariables.Container.Resolve<IUnitOfWork>();
        }

        /// <summary>
        /// 조회 여러개
        /// </summary>
        /// <returns></returns>
        public override IQueryable<PersonModel> Get()
        {
            return _uow.PeopleRepo.AllGetting();
        }

        /// <summary>
        /// 조회 1개
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected override PersonModel GetEntityByKey(int key)
        {
            return _uow.PeopleRepo.GettingByID(key);
        }

        /// <summary>
        /// Dispose
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            //_unitOfWork.Dispose();
            base.Dispose(disposing);
        }
        /// <summary>
        /// POST
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected override PersonModel CreateEntity(PersonModel entity)
        {
            _uow.PeopleRepo.Insert(entity);
            _uow.Save();
            return entity;
        }
        /// <summary>
        /// POST
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected override int GetKey(PersonModel entity)
        {
            return entity.Id;
        }

        /// <summary>
        /// PUT
        /// </summary>
        /// <param name="key"></param>
        /// <param name="update"></param>
        /// <returns></returns>
        protected override PersonModel UpdateEntity(int key, PersonModel update)
        {
            if (_uow.PeopleRepo.GettingByID(key) == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            _uow.PeopleRepo.Update(update);
            _uow.Save();
            return update;
        }

        /// <summary>
        /// PUT ?
        /// </summary>
        /// <param name="key"></param>
        /// <param name="patch"></param>
        /// <returns></returns>
        protected override PersonModel PatchEntity(int key, Delta<PersonModel> patch)
        {
            PersonModel user = _uow.PeopleRepo.GettingByID(key);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            patch.Patch(user);
            _uow.Save();
            return user;
        }

        /// <summary>
        /// DELETE
        /// </summary>
        /// <param name="key"></param>
        public override void Delete(int key)
        {
            PersonModel user = _uow.PeopleRepo.GettingByID(key);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            _uow.PeopleRepo.Delete(key);
            _uow.Save();
        }

    }

 

1-5. Web.config

ConnectionString을 추가해 준다.

 

  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-PCLSample.Web-20130627171150;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-PCLSample.Web-20130627171150.mdf" />
    <add name="PCLSampleContext" connectionString="Data Source=(local)\sqlexpress;Initial Catalog=PCLSample;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>

 

2. 위와 같이 하면 서버 구성은 완료가 된다.

다음 포스트는 클라이언트에서 DataServie를 추가하는 방법과 사용법에 대해 다루도록 하겠다.

 

반응형
댓글