Microsoft MVP성태의 닷넷 이야기
.NET Framework: 171. WCF - webHttpBinding 구현 예제 [링크 복사], [링크+제목 복사],
조회: 27237
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 171. WCF - webHttpBinding 구현 예제
; https://www.sysnet.pe.kr/2/0/833

.NET Framework: 172. WCF - webHttpBinding 윈도우 인증 구현 예제
; https://www.sysnet.pe.kr/2/0/834

.NET Framework: 173. WCF - webHttpBinding + IIS 6.0 윈도우 인증 구현 예제
; https://www.sysnet.pe.kr/2/0/835

.NET Framework: 175. WCF - webHttpBinding + PUT 메서드 구현
; https://www.sysnet.pe.kr/2/0/850





WCF - webHttpBinding 구현 예제


아래의 질문 덕분에 WCF의 webHttpBinding 예제를 구성해 보았습니다.

How to support Basic + Windows authentication mode in WCF(RESTful service) 
; https://www.sysnet.pe.kr/3/0/857

사실, WCF가 워낙 잘 추상화를 해놓아서 별로 할 것이 없는데다 아래와 같이 이미 영문 블로그에서 친절하게 소개해 놓았기 때문에 굳이 쓸 이유까지도 없어보이지만....

WCF - Using WebHttpBinding for REST services 
; https://asp-blogs.azurewebsites.net/kiyoshi/wcf-using-webhttpbinding-for-rest-services

그래도 직접 해보면 또 다른 묘미가 있기 때문에. ^^

일단, Contract 먼저 보면,

[ServiceContract(Namespace = "http://www.wcftest.com/")]
public interface IHelloWorld
{
    [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string year, string month, string day);
}

라는 식으로 정의하면 되는데, ResponseFormat의 경우 기본값이 Xml이므로 명시할 이유는 없지만 WebMessageFormat.Json으로도 변경할 수 있다는 가능성을 보여주기 위해 그대로 두었습니다. 구현 부분은 아래와 같이 일반 클래스 구현과 다른 점이 없습니다.

[ServiceBehavior]
public class CHelloWorld : IHelloWorld
{
    public string GetDate(string year, string month, string day)
    {
        return new DateTime(Convert.ToInt32(year), 
        	Convert.ToInt32(month), Convert.ToInt32(day)).ToShortDateString();
    }
}

서버 측은, 지저분한 web.config이 마음에 들지 않으니 다음과 같이 코드만으로 할 수 있고,

string baseAddress = "http://" + Environment.MachineName + ":9091/HelloService";

using (ServiceHost serviceHost = new ServiceHost(typeof(CHelloWorld), 
                                new Uri(baseAddress)))
{
    ServiceEndpoint endpoint = 
        serviceHost.AddServiceEndpoint(typeof(IHelloWorld), new WebHttpBinding(), "");
    endpoint.Behaviors.Add(new WebHttpBehavior());
    serviceHost.Open();

    Console.WriteLine("Press any key to exit...");
    Console.ReadLine();
}

클라이언트 측 코드 역시 web.config을 간결하게 하도록 다음과 같이 코드를 구성할 수 있습니다.

using (ChannelFactory<IHelloWorld> factory = 
        new ChannelFactory<IHelloWorld>(new WebHttpBinding(),
        new EndpointAddress(baseAddress)))
{
    factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
    IHelloWorld proxy = factory.CreateChannel();
    Console.WriteLine("Result of Get operation: {0}", proxy.GetDate("1990", "05", "01"));
}

이제 F5 키를 눌러서 실행 결과 확인!




REST 서비스의 재미있는 점을 짚고 넘어가야겠지요. 복잡한 Soap Envelope 구성 없이 요청/반환 구조가 URL에 의해서 이루어질 수 있는데요.

[WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string GetDate(string year, string month, string day);

위의 UriTemplate 지정으로 GetDate 웹 메서드를 호출하기 위해 다음과 같은 식으로 요청을 보내는 것이 가능합니다.

http://127.0.0.1:9091/HelloService/date/1995/10/10

오호... 마치 MVC의 URL Routing하는 것과 비슷한 구조를 제공해 주고 있습니다. 실제로 위와 같은 URL로 웹 브라우저의 주소 표시줄에 입력하고 실행하면 다음과 같은 결과를 얻을 수 있습니다.

ResponseFormat = WebMessageFormat.Xml인 경우,
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1995-10-10</string> 

ResponseFormat = WebMessageFormat.Json인 경우,
"1995-10-10"

첨부한 파일은 테스트가 바로 가능한 프로젝트 소스 코드를 포함하고 있습니다.



[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/24/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2011-03-23 09시54분
정성태

... 166  167  168  169  170  171  172  173  174  175  176  177  178  [179]  180  ...
NoWriterDateCnt.TitleFile(s)
553정성태12/16/200730125기타: 19. 인기 순위 정리 : 조회수 100 ~ 249회 글 목록
552정성태12/16/200723738기타: 18. 인기 순위 정리 : 조회수 000 ~ 099 회 글 목록
550정성태12/16/200723030Team Foundation Server: 23. TFS 2005에서 TFS 2008로 마이그레이션 [2]
549정성태12/16/200724352Team Foundation Server: 22. TFS 설정 - 주소를 도메인으로 변경
548정성태12/15/200741868오류 유형: 49. Report Server - 원격 서버에 연결할 수 없습니다
547정성태12/4/200730391.NET Framework: 98. .NET 비동기 Socket과 스레드
546정성태12/4/200721484Team Foundation Server: 21. Microsoft Office가 참조된 경우의 빌드 환경 구성
545정성태12/4/200728437Windows: 27. 눈으로 확인해 보는 ASLR 기능 [1]
544정성태11/25/200724084오류 유형: 48. VS.NET 2008 설치 오류 - Error code 1602 [5]
543정성태11/25/200727184개발 환경 구성: 31. ROBOCOPY XP026 버전 [1]
542정성태11/3/200742178VS.NET IDE: 55. XML/XSLT로 구현하는 매크로 확장 [5]파일 다운로드2
538정성태10/11/200728437스크립트: 10. VBScript - "Sub를 호출할 때는 괄호를 사용할 수 없습니다." [2]
537정성태9/28/200737313개발 환경 구성: 30. 64비트 OS에서의 ChartFX 라이선스 문제
536정성태9/12/200734280.NET Framework: 97. WCF : netTcpBinding에서의 각종 Timeout 값 설명 [11]
535정성태9/11/200731618.NET Framework: 96. WCF - PerSession에서의 클라이언트 연결 관리 [5]
534정성태9/3/200727212개발 환경 구성: 29. VHD 파일 크기 줄이기
533정성태9/2/200729802개발 환경 구성: 28. CA 서비스 - 사용자 정의 템플릿 유형 추가
532정성태9/2/200732056개발 환경 구성: 27. AD CA에서 Code Signing 인증서 유형 추가 방법
531정성태9/2/200727979.NET Framework: 95. WCF에서의 DataTable 사용
530정성태9/1/200724451.NET Framework: 94. WCF 예외에 대한 시행착오
529정성태8/31/200727549.NET Framework: 93. WCF - DataContract와 KnownType 특성 [1]
528정성태8/30/200721901오류 유형: 47. VPC - 네트워크 어댑터 MAC 주소 중복 오류
527정성태8/30/200732214Team Foundation Server: 20. 잠긴 파일을 강제로 해제 [2]
526정성태8/29/200722072오류 유형: 46. VS.NET 2008 - ASP.NET 디버깅 : Strong name validation failed.
525정성태8/27/200724237VS.NET IDE: 54. VS.NET 2008 - 새롭게 도입되는 XSD Schema Designer
524정성태8/23/200741813오류 유형: 45. 요청한 작업은, 사용자가 매핑한 구역이 열려 있는...
... 166  167  168  169  170  171  172  173  174  175  176  177  178  [179]  180  ...