Microsoft MVP성태의 닷넷 이야기
.NET Framework: 280. MVC3에서 JavaScriptSerializer 재정의하는 방법 [링크 복사], [링크+제목 복사],
조회: 26571
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

MVC3에서 JavaScriptSerializer 재정의하는 방법

MVC3에 새롭게 추가된 기능 중의 하나가 바로 JSON 개체 바인딩을 내장하고 있는 것입니다.

Introducing ASP.NET MVC 3 (Preview 1) - JavaScript and AJAX Improvements
; http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

그래서, Controller 측에서 다음과 같이 간단하게 메서드를 만들어 두면,

public class HomeController : Controller
{
    public JsonResult TestJson(MyObject param)
    {
        // System.Diagnostics.Trace.WriteLine(param.Text);
        return Json(null, JsonRequestBehavior.AllowGet);
    }
}

public class MyObject
{
    public string Text { get; set; }
}

클라이언트 측에서 ContentType = "application/json"으로 지정하는 것만으로 자연스럽게 호출하는 것이 가능합니다. (이 정도면, JSON용 서비스를 굳이 WCF에 맡길 필요가 없을 정도로 편리하군요. ^^)

string url = "http://localhost:2509/Home/TestJson";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
request.Method = "POST";

string txt = "{\"Text\":\"test\"}";

StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(txt);
sw.Close();

HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd();
resp.Close();

그런데, 한 가지 문제가 있습니다. 예를 들어, 전달되는 데이터를 다음과 같이 크게 해주면,

string txt = "{\"Text\":\"" + new string('c', 2097153) + "\"}";

이후의 HTTP 호출에서 클라이언트 측에 예외가 발생합니다.

System.Net.WebException occurred
  Message=The remote server returned an error: (500) Internal Server Error.
  Source=System
  StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at ConsoleApplication1.Program.Main(String[] args) in D:\...\Program.cs:line 35
  InnerException: 

별다른 오류 원인을 알 수 없어 답답한데요, 원인 규명을 위해 서버 측의 MVC Controller에 Execute 메서드를 다음과 같이 재정의해 주면,

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    try
    {
        base.Execute(requestContext);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Trace.WriteLine(ex.ToString());
        throw;
    }
}

오류 메시지로 다음과 같은 내용을 얻을 수 있습니다.

System.ArgumentException was unhandled by user code
  Message=Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input
  Source=System.Web.Extensions
  ParamName=input
  StackTrace:
       at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
       at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
       at System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext)
       at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
       at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
       ...[생략]...
       at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
       at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
       at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
  InnerException: 

실제로 MSDN 문서에서 JavaScriptSerializer.MaxJsonLength 속성을 보면,

JavaScriptSerializer.MaxJsonLength 
; https://docs.microsoft.com/ko-kr/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength

2,097,152(바이트 수가 아닌) 정숫값이 기본이고 유니코드 2바이트 기준으로 4MB 정도에 해당하는 입력을 받을 수 있다고 나옵니다. 불행히도 JavaScriptSerializer 개체를 개발자가 정의한 것이 아니라 MVC 내부적으로 생성되는 것이기 때문에 아마도 이 제한을 벗어나는 방법이 '외부 설정' 값으로 존재해야만 할 텐데요.

이에 대해 웹상에서 검색해 보면,

Can I set an unlimited length for maxJsonLength in web.config?
; http://stackoverflow.com/questions/1151987/can-i-set-an-unlimited-length-for-maxjsonlength-in-web-config

아래와 같은 설정값을 발견할 수 있습니다.

<configuration>  
   <system.web.extensions> 
       <scripting> 
           <webServices> 
               <jsonSerialization maxJsonLength="50000000"/> 
           </webServices> 
       </scripting> 
   </system.web.extensions> 
</configuration>

하지만, MSDN 문서 및 위의 덧글에서도 나오지만,

The value of the MaxJsonLength property applies only to the internal JavaScriptSerializer instance that is used by the asynchronous communication layer to invoke Web services methods. (MSDN: ScriptingJsonSerializationSection.MaxJsonLength Property)
Basically, the "internal" JavaScriptSerializer respects the value of maxJsonLength when called from a web method; direct use of a JavaScriptSerializer (or use via an MVC action-method/Controller) does not respect the maxJsonLength property, at least not from the systemWebExtensions.scripting.webServices.jsonSerialization section of web.config.


이 값은 웹 메서드가 비동기로 호출되었을 때에나 내부적으로 적용되는 값일 뿐 MVC3에서의 JSON 바인딩에서는 사용되지 않습니다.

실제로 .NET Reflector를 이용하여 System.Web.Mvc.JsonValueProviderFactory 개체에 정의된 GetDeserializedObject 메서드를 살펴보면 JavaScriptSerializer 개체를 생성하고 곧바로 DeserializeObject 메서드를 호출하는 것을 볼 수 있습니다.

private static object GetDeserializedObject(ControllerContext controllerContext)
{
    if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
    {
        return null;
    }
    string str = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
    if (string.IsNullOrEmpty(str))
    {
        return null;
    }
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.DeserializeObject(str);
}

따라서, 이 문제를 해결하려면 MVC3에서 JavaScriptSerializer를 사용하는 JSON 바인딩 지원 모듈을 사용자 정의해야 하는데요. 다행히 검색을 해보니, 이에 대한 방법이 제공되고 있습니다.

JSON / MVC (3P1) HttpPost - not getting it to work on my EF class
; http://tech-question.com/json-mvc-3p1-httppost-not-getting-it-to-work-on-my-ef-class-362041

현재 위의 자료는 삭제되었지만, 구글 검색의 "저장된 페이지" 기능을 이용해서 보면 다음과 같은 내용을 확인할 수 있습니다.

There's a bug in MVC 3 Preview 1 where the JsonValueProviderFactory is not registered by default. 

Having something like this in your Global.asax should help:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())

(비록 본문의 버그가 JavaScriptSerializer.MaxJsonLength 값을 늘리는 것과는 상관없는 이야기이지만!) ValueProviderFactory를 임의로 변경하는 것이 가능하다는 이야기인데요. 그렇다면 우리는 JavaScriptSerializer.MaxJsonLength 값을 변경해서 반환하는 ValueProviderFactory를 만들면 되는데... 어렵지 않게 다음과 같이 MVC 에서 제공되는 JsonValueProviderFactory 타입의 모든 코드를 재사용해주면 됩니다.

using System.Web.Mvc;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System;
using System.Web.Script.Serialization;
using System.Globalization;

public sealed class JsonValueProviderFactory2 : ValueProviderFactory
{
    // Methods
    private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
    {
        ...[생략: JsonValueProviderFactory의 AddToBackingStore 코드를 복사]...
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        ...[생략: JsonValueProviderFactory의 AddToBackingStore 코드를 복사]...

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.MaxJsonLength = Int32.MaxValue;
        return serializer.DeserializeObject(str);
    }

    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        ...[생략: JsonValueProviderFactory의 GetValueProvider 코드를 복사]...
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        ...[생략: JsonValueProviderFactory의 MakeArrayKey 코드를 복사]...
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        ...[생략: JsonValueProviderFactory의 MakePropertyKey 코드를 복사]...
    }
}

이제 이렇게 재정의한 JsonValueProviderFactory2 타입을 Global.asax에서 다음과 같이 추가합니다.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ValueProviderFactory jsonFactory = null;
    foreach (ValueProviderFactory factory in ValueProviderFactories.Factories)
    {
        if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
        {
            jsonFactory = factory;
            break;
        }
    }

    if (jsonFactory != null)
    {
        ValueProviderFactories.Factories.Remove(jsonFactory);
    }

    JsonValueProviderFactory2 factory2 = new JsonValueProviderFactory2();
    ValueProviderFactories.Factories.Add(factory2);
}

최종적으로 빌드하고 다시 테스트를 해보면 Action 메서드가 정상적으로 실행되는 것을 확인할 수 있습니다. ^^

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




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







[최초 등록일: ]
[최종 수정일: 7/17/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)
13667정성태7/7/20246623닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247700Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247884Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247482닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247491닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247413Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247523오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247864개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248243개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247918닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248098Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247858닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247788오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247937닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249250닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248488닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248410개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247968오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248289오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249345개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247765오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248201개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248868닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248323오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248201스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...