본문 바로가기

개발일지

Sent JSON parameter is null in WCF Service method

728x90

프로젝트를 진행중에 C# WCF 프로젝트에서 Restful 서비스를 만들어서 인터페이스 서비스를 개발해야 하는 작업을 하고 있다. 그런데... 좀 문제가 생겼다.  문제를 해결하기 전에 상황을 우선 작성하고 추후 문제를 해결하도록 한다.

1. 우선 프로젝트 생성

2. 필요 없는 소스는 제거함 (기본으로 생성되는 Service1.svc 제거)

3.  테스트 할 서비스를 추가 ( WCF 서비스(AJAX 사용) 이걸로 소스 추가 )

4. 생성한 이후 소스를 아래와 같이 함수를 추가한다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace RestfulWcfService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestfulService
    {
        // HTTP GET을 사용하려면 [WebGet] 특성을 추가합니다. 기본 ResponseFormat은 WebMessageFormat.Json입니다.
        // XML을 반환하는 작업을 만들려면
        //     [WebGet(ResponseFormat=WebMessageFormat.Xml)]을 추가하고
        //     다음 줄을 작업 본문에 포함시킵니다.
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // 여기에 작업 구현을 추가합니다.
            return;
        }

        // 여기에 작업을 추가하고 해당 작업을 [OperationContract]로 표시합니다.
        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json
            ,ResponseFormat = WebMessageFormat.Json
            , BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string ExecutePostRule(string requestJson)
        {
            return requestJson;
        }
    }
}

5. 이제 컴파일 하고 서버를 실행 (아래 화면 처럼 뜬다.)

6. 포스트맨으로 테스트 진행 (null 을 리턴하는게 문제임)

7. 다시 디버깅으로 소스 확인 (아직 원인 해결이 안되고 있음)

8. 혹시 몰라서 자바 client 소스를 작성하여 테스트 하였지만 똑같이 null로 전달이 되지 않음.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class restApiTest2 {
    
    public static String sendREST(String sendUrl, String jsonValue) throws IllegalStateException {
        String inputLine = null;
        StringBuffer outResult = new StringBuffer();
        
        try {
            System.out.println("REST API Start");
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);

            
            OutputStream os = conn.getOutputStream();
            os.write(jsonValue.getBytes("UTF-8"));
            os.flush();
            
            int responseCode = conn.getResponseCode();
            if (responseCode == 400) {
                System.out.println("400:: 해당 명령을 실행할 수 없음 (실행할 수 없는 상태일 때, 엘리베이터 수와 Command 수가 일치하지 않을 때, 엘리베이터 정원을 초과하여 태울 때)");
            } else if (responseCode == 401) {
                System.out.println("401:: X-Auth-Token Header가 잘못됨");
            } else if (responseCode == 500) {
                System.out.println("500:: 서버 에러, 문의 필요");
            } else {            
                // 리턴된 결과 읽기
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                while ((inputLine = in.readLine()) != null) {
                    outResult.append(inputLine);
                }
            }
            conn.disconnect();
            System.out.println("REST API End");
        }catch(Exception e) {
            e.printStackTrace();
        }
        return outResult.toString();
    }
    
    public static void main(String[] args) {
        restApiTest2 obj = new restApiTest2();       
        String message = "{ \"d\": \"AAAAA\"}";
        try {
            // 주소는 수시로 변경해야...
            String msgMap = sendREST("http://localhost:56187/RestfulService.svc/ExecutePostRule", message);
            System.out.println(msgMap);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

 

아직 해결중입니다. 이 상황에 대하여 혹시 누군가 이글을 읽게 되신다면 도움 부탁드리며 빨리 해결이 된다면 해결방법을 다시 올리도록 하겠습니다.

해결하기 위한 시도 1

여기 프로젝트 소스 다운받아서 xml 방식이기는 하지만 파라메터 수신을 받음. 일단 이 방법도 확인이 필요

https://www.codeproject.com/Articles/201901/CREATE-RESTful-WCF-Service-API-Using-POST-Step-By

 

CREATE RESTful WCF Service API Using POST: Step By Step Guide

This article will help you to create RESTful WCF POST API. I have given Client and Server example which is really easy to understand.

www.codeproject.com

일단 응답과 파라메터 값이 null이 아님. xml 방식으로는 되는데... json 방식으로는 null 파라메터 받음. 아 짜증...

string 파라메터 받는데 쉬울줄 알았는데 가장 쉬운게 가장 어려운 듯...

그래서 대안으로 XElement 타입으로 받는것으로 일단 수정 해서 작업 한다. 나중에 또 알게되면 다시 재작업 함.

https://stackoverflow.com/questions/58295064/how-to-transfer-xml-file-from-postman-to-web-api-using-post-method-and-return-it

 

How to transfer xml file from postman to web api using post method and return it back?

Here I have the request body. P.s. Content-Type: text/xml in headers <

stackoverflow.com

 

728x90