WCF Create REST WebService and GET/POST Testing with Fiddler

 WCF로 간단하게 SOAP를 이용해서 Helloworld WebService를 만들어봤습니다. 이번에는 REST 웹 서비스를 만들어보겠습니다.


1. WCF REST 웹서비스 생성

namespace WCFServiceTest
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        string GetTest(string strTemp);

        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string PostTest(string strTemp);
    }
}

 먼저 Helloworld WebService를 그대로 만들고 생성된 IService1.cs의 내용을 위와같이 수정해줍니다. GetTest라는 GET 메소드와 PostTest라는 POST 메소드를 만들었습니다. ResponseFormat는 모두 JSON입니다.


namespace WCFServiceTest
{
    public class Service1 : IService1
    {
        public string GetTest(string strTemp)
        {
            string response = strTemp + " success get";
            return response;
        }

        public string PostTest(string strTemp)
        {
            string response = strTemp + " success Post";
            return response;
        }
    }
}

 마찬가지로 Service1.svc.cs도 위와같이 수정해서 메소드 구현부를 작성합니다. 간단하게 요청하면서 넘어온 인자에 success get과 success post를 추가해서 스트링을 반환해줍니다.


<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <!-- Add -->
    <services>
      <service name="WCFServiceTest.Service1">
        <endpoint address="Http"
binding="webHttpBinding"
contract="WCFServiceTest.IService1"
behaviorConfiguration="webHttp"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <!-- Add -->
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>  
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

 마지막으로 Web.config를 수정합니다. 붉은색부분이 기본 Web.config에서 추가해줘야할 부분입니다. 바인딩을 webHttpBinding을 해줘야 REST로 처리할 수 있는 기본적인 바인딩입니다. address에 서비스할 웹주소를 설정해줍니다. contract에는 개발중인 웹서비스프로젝트명.웹서비스명 으로 지정합니다. 이와같이 수정하지 않으면 테스트중 HTTP 400 잘못된 요청입니다 에러가 발생합니다.


2. 피들러로 웹서비스 테스트


 피들러(Fiddler)라는 것으로 테스팅을 진행합니다. 웹 개발자들에게는 트랙픽 모니터링이나 개발 테스팅, 디버깅등을 하는데 필수 유틸리티라고 하네요. 게대가 무료입니다. 찰스(Charles)라고도 있지만 이것은 유료버전이네요. 설치가 간단해서 설치과정은 생략합니다.

 피들러를 실행 후 오른쪽 탭 메뉴중에 Composer를 클리합니다. 그리고 Parsed 탭에서 GET이 선택된 상태로

http://localhost:54045/Service1.svc/http/GetTest?strTemp=WestWoodForever

 위와같이 스샷과 같이 입력 후 Execute를 클릭하면 스샷과 같이 Result 200이 떨어집니다. http는 Web.config에서 설정한 어드레스이고 GetTest는 GET 메소드, strTemp와 WestWoodForever는 인자값입니다.

 왼쪽에 결과값을 더블클릭해보면 Inspectors 탭이 열립니다. TextView탭을 통해서 "WestWoodForever success get" 결과값을 확인할 수 있습니다. GET은 웹브라우저에서도 테스트 가능합니다.

 이번엔 POST 테스트입니다. GET과 마찬가지로 Composer 탭에서 하는데 GET으로 된 콤보박스를 POST로 변경하고

http://localhost:54045/Service1.svc/http/PostTest

 위와 같이 주소를 입력 후 하단에 RequestBody에는

{"strTemp": "WestWoodForever"}

 json 포멧으로 입력해줍니다. 그리고 Execute를 하면,

 HTTP/1.1 400 Bad Request 에러가 발생합니다. 웹브라우저에서 테스트했다면 '메서드를 사용할 수 없습니다' 에러가 발생했을텐데요,

 Composer탭에서 Request Headers부분에 스샷과 같이

Content-Type: application/json; charset=UTF-8

 을 추가해줍니다.

 그러면 POST 테스트도 처리된 것을 확인할 수 있습니다.

msdn : WCF 웹 HTTP 프로그래밍 모델

댓글

이 블로그의 인기 게시물

'xxx.exe' 프로그램을 시작할 수 없습니다. 지정된 파일을 찾을 수 없습니다.

goorm IDE에서 node.js 프로젝트로 Hello World Simple Server 만들어 띄워보기

애드센스 수익을 웨스턴 유니온으로 수표대신 현금으로 지급 받아보자.