Microsoft MVP성태의 닷넷 이야기
.NET Framework: 175. WCF - webHttpBinding + PUT 메서드 구현 [링크 복사], [링크+제목 복사],
조회: 17493
글쓴 사람
정성태 (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)
13276정성태3/5/20234797.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20235033.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234600.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234362.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234605오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234589오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20234097.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234736스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20235252개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20235141.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234780오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234662.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20236256스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234415개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235496디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234863Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234607오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234762.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234584오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234679.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235429개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234846오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234764Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235585Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20234388오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234752스크립트: 44. 파이썬의 3가지 스레드 ID
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...