Microsoft MVP성태의 닷넷 이야기
.NET Framework: 175. WCF - webHttpBinding + PUT 메서드 구현 [링크 복사], [링크+제목 복사],
조회: 17392
글쓴 사람
정성태 (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)
13616정성태5/3/2024116닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/2024118닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/2024200닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/2024438닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/2024415오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024678닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/2024751닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024854닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20241039닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20241056닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20241003닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024978닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024985오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20241036닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20241015닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20241026닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241074닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024978닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/20241024닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20241059닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241136닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241087닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241112닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241129닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241544C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동 [1]
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...