Microsoft MVP성태의 닷넷 이야기
.NET Framework: 175. WCF - webHttpBinding + PUT 메서드 구현 [링크 복사], [링크+제목 복사],
조회: 17502
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

webHttpBinding + PUT 메서드 구현


지난 이야기에 이어서.
WCF - webHttpBinding + IIS 6.0 윈도우 인증 구현 예제
; https://www.sysnet.pe.kr/2/0/835

이번에는 RESTful 서비스에 허용되는 PUT 메서드에 대해서 알아보겠습니다.

참고로, Windows 2003에서는 PUT 메서드가 svc 확장자에 대해 기본적으로는 허용되어 있지 않기 때문에, 우선 "웹 사이트" 속성창에서 다음과 같이 SVC 확장자에 대한 PUT 메서드 전달을 허용해 두어야 합니다.

enable_put_method_on_svc_1.png




GET 메서드의 경우 WebGet 특성으로 지정되었던 반면, PUT 메서드에 대해서는 WebInvoke 특성을 지정해야 합니다. 예를 들면 더 직관적이겠죠!

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

    [WebInvoke(Method = "PUT", UriTemplate = "putData/{year}")]
    [OperationContract]
    string PutData(string year);
}

위에서 정의된 PutData 메서드에서는 UriTemplate을 사용해서 인자 전달을 받고 있는데요. 이처럼 단순 인자뿐만 아니라 PUT/GET에 대한 웹 메서드들은 모두 구조체를 전달할 수 있습니다. GET 방식의 경우에는 UriTemplate에서 보는 것처럼 Query String으로 전달이 가능한데요. 이에 대해서는 다음의 글에서 잘 설명해 주고 있습니다.

Passing a JSON object to a WCF service with jQuery
; http://www.dennydotnet.com/post/Passing-a-JSON-object-to-a-WCF-service-with-jQuery.aspx

즉, (JSON 포맷의 경우) 아래와 같이 주소에 이은 Query Parameter로 전달하면 되는데,

http://www.dennydotnet.com/Service.svc/DoWork/?p={ "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] }

그냥 전달하면 안되고, Url Encoding을 해줘야 한다고 합니다.

http://www.dennydotnet.com/Service.svc/DoWork/?p=%7b+%22Name%22%3a%22Denny%22%2c+%22Age%22%3a23%2c+%22Shoes%22%3a%5b%22Nike%22%2c%22Osiris%22%2c%22Etnies%22%5d+%7d%3b 

반면에, PUT 메서드의 경우는 HTTP Body 영역을 이용한 전달까지 가능합니다.
이 경우에 직렬화 하는 방법은 Xml과 Json 방식이 있는데, Json 방식은 인자의 타입을 그대로 적용하는 것이 가능하지만 Xml 방식은 XmlElement로 전달받아서 처리해야 합니다.

// XML 직렬화 
[WebInvoke(Method = "PUT", UriTemplate = "/putData2", BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
string PutData2(XmlElement my);

// JSON 직렬화
[WebInvoke(Method = "PUT", UriTemplate = "/putData3", RequestFormat = WebMessageFormat.Json
                                                    , ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string PutData3(Person my);

이제 위의 코드를 호출하기 위한 클라이언트 측 코드를 살펴볼까요?

지난 예제에서도 살펴본 것처럼, webHttpBinding은 WCF 프록시 뿐만 아니라 HttpWebRequest로도 호출이 됩니다. 실제로 요청 Payload를 확인해 보면 다음과 같은데,

====== XML 포맷의 경우 ======
PUT /HelloService/CHelloWorld.svc/myPut2 HTTP/1.1
Content-Length: 154
Content-Type: text/xml
Authorization: Negotiate oXcwdaADCgEBoloEWE5UTE1TU1AAAwAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAADXCiOIGAbAdAAAADxLbmbM6Ne2M6pm8P8w30VKjEgQQAQAAAPUXp1AtIpqEAAAAAA==
Host: localhost

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="Test2" Age="17" />

====== JSON 포맷의 경우 ======
PUT /HelloService/CHelloWorld.svc/putData3 HTTP/1.1
Content-Length: 24
Content-Type: application/json
Authorization: Negotiate oXcwda...[생략]...AA==
Host: localhost

{"Age":16,"Name":"Test"}

그러하니 당연히 코드는 위의 내용을 맞춰주면 되겠지요! ^^


// PUT 메서드 테스트 + XML 포맷
reqAddress = string.Format("{0}/putData2", baseAddress);
req = WebRequest.Create(reqAddress) as HttpWebRequest;
req.Method = "PUT";
req.ContentType = "text/xml";
req.UseDefaultCredentials = true;

Person person = new Person();
person.Name = "Test2";
person.Age = 17;

MemoryStream ms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Person));
xs.Serialize(ms, person);
ms.Position = 0;
req.ContentLength = ms.Length;

Stream oStream = req.GetRequestStream();
oStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
oStream.Close();

using (WebResponse response = req.GetResponse())
{
    Stream stream = response.GetResponseStream();
    StreamReader sr = new StreamReader(stream);
    string text = sr.ReadToEnd();
    Console.WriteLine(text);
}

// PUT 메서드 테스트 + JSON 포맷
reqAddress = string.Format("{0}/putData3", baseAddress);
req = WebRequest.Create(reqAddress) as HttpWebRequest;
req.Method = "PUT";
req.ContentType = "application/json";
req.UseDefaultCredentials = true;

oStream = req.GetRequestStream();

DataContractJsonSerializer ser =
      new DataContractJsonSerializer(typeof(Person));

person = new Person();
person.Name = "Test";
person.Age = 16;

ms = new MemoryStream();
ser.WriteObject(ms, person);
ser.WriteObject(oStream, person);
ms.Position = 0;
StreamReader sReader = new StreamReader(ms);
string serialized = sReader.ReadToEnd();
Console.WriteLine(serialized);
oStream.Close();

using (WebResponse response = req.GetResponse())
{
    Stream stream = response.GetResponseStream();
    StreamReader sr = new StreamReader(stream);
    string text = sr.ReadToEnd();
    Console.WriteLine(text);
}




마지막으로, XML 직렬화의 경우에도 JSON 방식처럼 XmlElement가 아닌 해당 타입을 직접 받는 것이 가능합니다. 방법이 매우 간단한데요. 다음과 같이 XmlSerializerFormat 특성만 추가해 주면 됩니다.

// XML 직렬화 + XmlSerializerFormat
[WebInvoke(Method = "PUT", UriTemplate = "/putData4")]
[OperationContract]
[XmlSerializerFormat]
string PutData4(Person my);

이 정도면, webHttpBinding 사용에 대해서는 웬만큼 다 살펴본 것 같군요. ^^

첨부한 파일은 위의 코드를 모두 담고 있는 예제 솔루션입니다.



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







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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13453정성태11/23/20232655오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232717닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232873닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232684닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232848개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20233101닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20233071닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232995닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20233249Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20233018닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232902개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232671개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20233110닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232660Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20233321닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232924닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20233082닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233294닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233238닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20233043스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232615스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232843오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20233231스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20233031닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233232닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233414닷넷: 2151. C# 12 - ref readonly 매개변수
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...