Microsoft MVP성태의 닷넷 이야기
.NET Framework: 280. MVC3에서 JavaScriptSerializer 재정의하는 방법 [링크 복사], [링크+제목 복사],
조회: 20169
글쓴 사람
정성태 (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)
13583정성태3/25/20241710Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20242059Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20242150개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241637닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20242050오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20242269닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20242558닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20242005닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20242207닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20242076닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241988닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20242241닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20242090닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20242011닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241949닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20242042닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241997오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20242061오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241929닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20242164Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20242146디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20242129오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242255닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242352디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20243208오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242501닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...