Microsoft MVP성태의 닷넷 이야기
.NET Framework: 175. WCF - webHttpBinding + PUT 메서드 구현 [링크 복사], [링크+제목 복사],
조회: 17490
글쓴 사람
정성태 (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)
13530정성태1/15/20242345닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242346닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242490Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242349오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242440닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242346오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242400오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242202오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242410닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242518닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242289오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242257닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242504닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242330스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242420닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242779닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242438개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242378닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242336개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242327닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242227닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242362오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242404오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20243148닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232658닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20233262닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...