Microsoft MVP성태의 닷넷 이야기
.NET Framework: 280. MVC3에서 JavaScriptSerializer 재정의하는 방법 [링크 복사], [링크+제목 복사],
조회: 20200
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
12907정성태1/9/20227014오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20227662.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20227294오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20229323개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227905.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20228001오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20228043오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20229686개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20229296개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20229796.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20228589.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202211614.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219986.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
12894정성태12/30/20217965.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20219571.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/20217449기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/20217342스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/20217540VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/20219971.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/20218057.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/202110225오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/20217964스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/20218232오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20217263개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/20218279오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/20217318개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...