성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Reordering on an Alpha processor ;...
[정성태] 공유 감사합니다. ^^ 참고로, WPF에서 WindowsF...
[Tom Lee] 답변 감사합니다. 나름의 해결책 연구해보고 여기에도 공유해봅니다...
[정성태] 아래의 글을 보면, MoveWindow 하면 될 듯한데요. ^^...
[Tom Lee] 안녕하세요 올려주신 글 참고하여 WPF 어플리케이션 안에 Uni...
[정성태] A graphical depiction of the steps ...
[정성태] 질문을 주셔서 출판사 측에 문의를 했습니다. 약 한 달 정도 후...
[Thorondor
] @정성태 개인 블로그인데도 거의 커뮤니티 급 인 것 같아요. 요...
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <div style='font-family: 맑은 고딕, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>webHttpBinding + PUT 메서드 구현</div><br /> <br /> 지난 이야기에 이어서.<br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > WCF - webHttpBinding + IIS 6.0 윈도우 인증 구현 예제 ; <a target='_tab' href='/2/0/835'>http://www.sysnet.pe.kr/2/0/835</a> </pre> <br /> 이번에는 RESTful 서비스에 허용되는 PUT 메서드에 대해서 알아보겠습니다. <br /> <br /> 참고로, Windows 2003에서는 PUT 메서드가 svc 확장자에 대해 기본적으로는 허용되어 있지 않기 때문에, 우선 "웹 사이트" 속성창에서 다음과 같이 SVC 확장자에 대한 PUT 메서드 전달을 허용해 두어야 합니다.<br /> <br /> <img alt='enable_put_method_on_svc_1.png' src='/SysWebRes/bbs/enable_put_method_on_svc_1.png' /><br /> <br /> <hr style='width: 50%' /><br /> <br /> GET 메서드의 경우 WebGet 특성으로 지정되었던 반면, PUT 메서드에 대해서는 WebInvoke 특성을 지정해야 합니다. 예를 들면 더 직관적이겠죠!<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > [ServiceContract(Namespace = "http://www.wcftest.com/")] public interface IHelloWorld { [WebGet(...)] [OperationContract] string GetDate(string year, string month, string day); <b style='COLOR: blue'>[WebInvoke(Method = "PUT", UriTemplate = "putData/{year}")]</b> [OperationContract] string PutData(string year); } </pre> <br /> 위에서 정의된 PutData 메서드에서는 UriTemplate을 사용해서 인자 전달을 받고 있는데요. 이처럼 단순 인자뿐만 아니라 PUT/GET에 대한 웹 메서드들은 모두 구조체를 전달할 수 있습니다. GET 방식의 경우에는 UriTemplate에서 보는 것처럼 Query String으로 전달이 가능한데요. 이에 대해서는 다음의 글에서 잘 설명해 주고 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > Passing a JSON object to a WCF service with jQuery ; <a target='_tab' href='http://www.dennydotnet.com/post/Passing-a-JSON-object-to-a-WCF-service-with-jQuery.aspx'>http://www.dennydotnet.com/post/Passing-a-JSON-object-to-a-WCF-service-with-jQuery.aspx</a> </pre> <br /> 즉, (JSON 포맷의 경우) 아래와 같이 주소에 이은 Query Parameter로 전달하면 되는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > http://www.dennydotnet.com/Service.svc/DoWork/?<b style='COLOR: blue'>p={ "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] }</b> </pre> <br /> 그냥 전달하면 안되고, Url Encoding을 해줘야 한다고 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > http://www.dennydotnet.com/Service.svc/DoWork/?<b style='COLOR: blue'>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</b> </pre> <br /> 반면에, PUT 메서드의 경우는 HTTP Body 영역을 이용한 전달까지 가능합니다.<br /> 이 경우에 직렬화 하는 방법은 Xml과 Json 방식이 있는데, Json 방식은 인자의 타입을 그대로 적용하는 것이 가능하지만 Xml 방식은 XmlElement로 전달받아서 처리해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > // XML 직렬화 [WebInvoke(Method = "PUT", UriTemplate = "/putData2", <b style='COLOR: blue'>BodyStyle = WebMessageBodyStyle.Bare</b>)] [OperationContract] string PutData2(<b style='COLOR: blue'>XmlElement my</b>); // JSON 직렬화 [WebInvoke(Method = "PUT", UriTemplate = "/putData3", RequestFormat = WebMessageFormat.Json , ResponseFormat = WebMessageFormat.Json)] [OperationContract] string PutData3(<b style='COLOR: blue'>Person my</b>); </pre> <br /> 이제 위의 코드를 호출하기 위한 클라이언트 측 코드를 살펴볼까요?<br /> <br /> 지난 예제에서도 살펴본 것처럼, webHttpBinding은 WCF 프록시 뿐만 아니라 HttpWebRequest로도 호출이 됩니다. 실제로 요청 Payload를 확인해 보면 다음과 같은데, <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > ====== XML 포맷의 경우 ====== PUT /HelloService/CHelloWorld.svc/myPut2 HTTP/1.1 Content-Length: 154 Content-Type: text/xml Authorization: Negotiate oXcwdaADCgEBoloEWE5UTE1TU1AAAwAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAADXCiOIGAbAdAAAADxLbmbM6Ne2M6pm8P8w30VKjEgQQAQAAAPUXp1AtIpqEAAAAAA== Host: localhost <b style='COLOR: blue'><?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" /> </b> ====== JSON 포맷의 경우 ====== PUT /HelloService/CHelloWorld.svc/putData3 HTTP/1.1 Content-Length: 24 Content-Type: <b style='COLOR: blue'>application/json</b> Authorization: Negotiate oXcwda...[생략]...AA== Host: localhost <b style='COLOR: blue'>{"Age":16,"Name":"Test"}</b> </pre> <br /> 그러하니 당연히 코드는 위의 내용을 맞춰주면 되겠지요! ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > // 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); } </pre> <br /> <hr style='width: 50%' /><br /> <br /> 마지막으로, XML 직렬화의 경우에도 JSON 방식처럼 XmlElement가 아닌 해당 타입을 직접 받는 것이 가능합니다. 방법이 매우 간단한데요. 다음과 같이 XmlSerializerFormat 특성만 추가해 주면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; width: 800px; background-color: #fbedbb; overflow-x: scroll; font-family: Consolas, Verdana;' > // XML 직렬화 + XmlSerializerFormat [WebInvoke(Method = "PUT", UriTemplate = "/putData4")] [OperationContract] <b style='COLOR: blue'>[XmlSerializerFormat]</b> string PutData4(Person my); </pre> <br /> 이 정도면, webHttpBinding 사용에 대해서는 웬만큼 다 살펴본 것 같군요. ^^<br /> <br /> <a target='_tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=527&boardid=331301885'>첨부한 파일</a>은 위의 코드를 모두 담고 있는 예제 솔루션입니다.<br /> <br /><br /><hr /><span style='color: Maroon'>[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
4141
(왼쪽의 숫자를 입력해야 합니다.)