Microsoft MVP성태의 닷넷 이야기
.NET Framework: 237. WCF AJAX 서비스와 JavaScript 간의 DateTime 연동 [링크 복사], [링크+제목 복사],
조회: 22025
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)

WCF AJAX 서비스와 JavaScript 간의 DateTime 연동

일단, JSON 개체를 AJAX 서비스에 전달하는 방법은 다음의 글을 참조하시고.

Using complex types to make calling services less… complex
; http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

여기서는, 자바스크립트에서 Date 타입을 전달/반환받는 방법을 살펴보겠습니다.

우선, AJAX 서비스 측에서 DateTime을 반환해주는 값을 자바스크립트에서 사용하는 것을 다뤄보기 위해 다음과 같이 간단한 예제 코드를 만들어 보겠습니다.

===== 서버 측 AJAX 서비스 =====
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AjaxService
{
    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    public DateTime DoWork()
    {
        HttpContext.Current.Response.Expires = 0;

        return DateTime.UtcNow;
    }
}

===== 클라이언트 측 자바스크립트 =====
<script type="text/javascript">

    function ajaxJson(serviceUrl, httpMethod, method, data, callback, error) {
        var url = serviceUrl + "/" + method;
        $.ajax({
            url: url,
            data: data,
            type: httpMethod,
            processData: true,
            contentType: "application/json",
            timeout: 1000 * 10,
            dataType: "json",
            success: callback,
            error: error
        });
    }

    function DoWorkResponse(result) {
        var dateNow = result.d;

        alert("result: " + dateNow);
    }

    function DoWorkError() {
    }

    ajaxJson(ajaxRootUrl, "GET", "DoWork", "", DoWorkResponse, DoWorkError);
        
</script>

이렇게 실행해서 반환받은 값은 다음과 같은 JSON 형태로 직렬화 되어 있습니다.

{"d":"\/Date(1313673383715)\/"}

자바 스크립트에서는 이렇게 구한 'd' 속성값이 '문자열'로 역직렬화된다는 것을 차치하고라도, Date(...) 내부에 있는 숫자의 값이 궁금합니다. 이에 대해서는 다음의 글에서 설명되고 있는데요.

DateTime to javascript date
; http://stackoverflow.com/questions/2404247/datetime-to-javascript-date

C#의 DateTime 기준으로, "1970년 1월 1일 날짜를 뺀 총 ms(Millisecond) 값"인데 C# 코드에서 직접 이 값을 구하려면 위의 글에 달린 댓글대로 다음과 같이 처리할 수 있습니다.

DateTime now = DateTime.UtcNow;
System.Diagnostics.Debug.WriteLine(now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds); // 소수점 자리가 생기지만!

이쯤 되면 위의 계산에서 사용된 "1970년 1월 1일"이라는 특별한 날짜가 의아스러울 텐데요. 역시 다음의 글을 읽어보시면 도움이 되실 것입니다.

time
; http://jangyeoh.mzin.net/V0/lecture/language/c/time.txt

(즉, "Epoch time == 1970년 1월 1일"인데 현재 C언어에서는 long 형으로 초 단위 시간기록을 하고 있어서 2038년 이상의 시간 표시를 할 수 없다고 합니다.)

Epoch 기준 시간 자체를 C# DateTime의 Ticks로 바꾸면 어떤 값이 나올까요?

new DateTime(1970, 1, 1).Ticks
    ==> 621355968000000000

이 숫자는 자바와 C#의 시간 연동을 해본 분이라면 낯이 익을 텐데요. 실제로 자바의 System.currentTimeMillis()가 반환하는 값은 다음의 C# 코드와 동일합니다.

System.currentTimeMillis() == (System.DateTime.UtcNow.Ticks - 621355968000000000) / TimeSpan.TicksPerMillisecond;

정리해 보면, AJAX 서비스에서는 DateTime에 대해서 직렬화를 Epoch 기준의 시간으로 변환한 ms(Millisecond) 값을 "/Date(...)/"로 감싼 문자열로 반환하고 있습니다.

그럼, 이 값을 자바스크립트의 Date 개체로 바꾸려면 어떻게 해야 할까요? 다행히 Date 개체는 Epoch 기준의 ms 값을 받는 생성자를 가지고 있기 때문에 다음과 같은 eval 구문으로 "/" 문자를 없애고 직접 Date 개체를 생성할 수 있습니다.

function DoWorkResponse(result) {
    var now = eval("new " + result.d.replace(/\//g, '') + ";"); // 예) eval("new Date(1313673383715);");
    alert(now);
}




다음은, 자바스크립트에서 AJAX 서비스로 date 타입을 전달하는 것을 알아보겠습니다.

'직관적인 기준'으로 보면 다음과 같이 구현해 줄 수 있을 것입니다.

===== 서버 측 AJAX 서비스 =====
[WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void SendTime(DateTime now)
{
    HttpContext.Current.Response.Expires = 0;

    System.Diagnostics.Debug.WriteLine(now);
}

===== 클라이언트 측 자바스크립트 =====
var dateTimeNow = new Date();
ajaxJson(ajaxRootUrl, "GET", "SendTime", "now=" + dateTimeNow, SendTimeResponse, SendTimeError);

호출이 잘 될까요? 아쉽게도 오류가 발생하는데, 왜냐하면 다음과 같은 형식의 문자열로 직렬화되어 GET 메서드의 파라미터로 전달되기 때문입니다.

===== 요청 =====
GET http://localhost:26514/AjaxService.svc/SendTime?now=Fri%20Aug%2019%2000:02:11%20UTC+0900%202011 HTTP/1.1
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Accept: application/json, text/javascript, */*
...[생략]...

===== 반환 =====
HTTP/1.1 500 Internal Server Error
Content-Length: 509
Content-Type: application/json; charset=utf-8
jsonerror: true
...[생략]...

{"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the  configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.","StackTrace":null}

"Fri%20Aug%2019%2000:02:11%20UTC+0900%202011"과 같은 값으로 직렬화되어 넘어가는 값을 AJAX 서비스는 정상적으로 DateTime 값으로 변환하지 못하고 예외를 발생합니다.

그럼 어떻게 전달해야 할까요? 맞습니다. 반환받을 때와 동일하게 "\/Date(1313673383715)\/"와 같은 식으로 전달해 주어야 합니다. 다행히 자바스크립트에서 epoch 기준의 시간으로 변환하는 것은 어렵지 않은데, 대신 JSON 포맷 및 UrlEncode와 같은 부가적인 추가 작업이 필요해서 다음과 같이 다소 번거로운 처리를 해주어야 합니다.

function ToEpochBasedTimeForGET(dateObj) {
    return "\"\\/Date(" + dateObj.getTime() + ")\\/\"";  // "\/Date(1313673383715)\/"  (인용 부호 포함해서!)
}

var dateTimeNow = new Date();
ajaxJson(ajaxRootUrl, "GET", "SendTime", "now=" + escape(ToEpochBasedTimeForGET(dateTimeNow)), SendTimeResponse, SendTimeError);

===== HTTP 요청 =====
GET http://localhost:26514/AjaxService.svc/SendTime?now=%22%5C/Date%281313682191870%29%5C/%22 HTTP/1.1
Content-Type: application/json
...[생략]...

물론, POST/PUT 방식이라면 GET 방식에서 필요했던 UrlEncode 과정을 생략해 줄 수 있는데, 대신 JSON 직렬화 자체에 변수명을 함께 전달해 주어야 합니다.

===== 서버 측 AJAX 서비스 =====
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void SendTime2(DateTime now)
{
    HttpContext.Current.Response.Expires = 0;

    System.Diagnostics.Debug.WriteLine(now + ", Kind: " + now.Kind);
}

===== 클라이언트 측 자바스크립트 =====
function ToEpochBasedTime(paramName, dateObj) {
    return "{ \"" + paramName + "\": \"\\/Date(" + dateObj.getTime() + ")\\/\" }"; // { "now":  "\/Date(1313673383715)\/" }
}

var dateTimeNow = new Date();
ajaxJson(ajaxRootUrl, "POST", "SendTime2", ToEpochBasedTime("now", dateTimeNow), SendTimeResponse, SendTimeError);

===== HTTP 요청 =====
POST http://localhost:26514/AjaxService.svc/SendTime2 HTTP/1.1
Content-Type: application/json
Host: localhost:26514
Content-Length: 36
...[생략]...

{ "now": "\/Date(1313682191870)\/" }

이 정도면, 더 이상의 설명은 필요 없겠지요. ^^

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/17/2021]

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

비밀번호

댓글 작성자
 



2016-10-08 11시54분
시간 정보 표현 방식 (Time Expressions)
; http://blog.naver.com/lovepeace/220830360898
정성태

1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13542정성태1/30/20242084오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242185VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242312Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242412개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242458닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242561닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242621닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242525닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242277닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242505닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242389닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242321닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242221닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242103닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242247Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242160오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242251닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242214오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242301오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242103오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242247닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242315닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242085오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242149닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242394닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242221스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...