web.config에서 maxJsonLength의 길이를 무제한으로 설정할 수 있습니까?


663

jQuery의 자동 완성 기능을 사용하고 있습니다. 17000 개 이상의 레코드 목록을 검색하려고하면 (각 문자의 길이는 10 자 이하 여야 함) 길이를 초과하여 오류가 발생합니다.

예외 정보 :
예외 유형 : InvalidOperationException
예외 메시지 : JSON JavaScriptSerializer를 사용한 직렬화 또는 역 직렬화 중에 오류가 발생했습니다. 문자열의 길이가 maxJsonLength 특성에 설정된 값을 초과합니다.

나는에 대한 길이 제한을 설정할 수 maxJsonLength있는 web.config? 그렇지 않은 경우 설정할 수있는 최대 길이는 얼마입니까?


1
언급 할만한 것이 분명하기 때문에 이미 생각이 든다면 실례합니다. Json 문자열에는 각 레코드 주위에 중괄호, 각 필드 이름 [및 값] 주위의 따옴표, 필드 이름 및 값이 포함됩니다. 따라서 필드 이름을 단일 문자로 설정하고 값이 문자열이 아닌 경우 필드 유형을 올바르게 설정하여 따옴표가 포함되지 않도록하는 것이 유용 할 수 있습니다.
— MichaelJTaylor

답변:


719

참고 : 이 답변은 웹 서비스에만 적용됩니다 .Controller 메서드에서 JSON을 반환하는 경우 https://stackoverflow.com/a/7207539/1246870 아래 에서이 SO 답변을 읽으십시오.


MaxJsonLength 속성이 제한 될 수 없다, 정수 속성입니다 기본값 102,400 (100,000).

MaxJsonLengthweb.config 에서 속성을 설정할 수 있습니다 .

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

153
정수이므로 설정할 수있는 최대 값은 다음과 같습니다. 2147483644
— David Espart

57
@despart : 당신은 2 147 483647을 의미합니다.
— Dercsár

6
@ kmcc049, 당신이 질문 보면, 영업 이익이되기 때문에 IMO 값이 잘못되지 않습니다 요구하고 있지 "maxJsonLength의 기본값은 무엇?" (BTW, 두 번째로 가장 많이 투표 된 답변은이 질문에 대한 답입니다. 잘못된 질문입니다), 그는이 속성을 "무제한"으로 설정하려고하지만 정수이므로 가능한 최대 값은 2147483647@depsart 및 @ Descár가 지적합니다.
— CMS

11
위대한하지만 MVC의 사용이 문제가 발생하는 경우 아래의 참고 @ 데이비드 머독의 대답 return Json()이나 뭐
— BritishDeveloper

3
@ Dercsár : 요점은 무엇입니까? 2147483644는 1024로 완전히 나눌 수있는 가장 큰 정수입니다.
— naveen

461

MVC 4를 사용 하는 경우이 답변 도 확인하십시오 .


여전히 오류가 발생하는 경우 :

  • maxJsonLengthweb.config에서 속성을 최대 값으로 설정 한 후
  • 데이터 길이가이 값보다 작다는 것을 알고 있습니다.
  • JavaScript 직렬화에 웹 서비스 방법을 사용하지 않습니다

당신의 문제는 다음과 같습니다.

MaxJsonLength 속성 값은 웹 서비스 메서드를 호출하기 위해 비동기 통신 계층에서 사용하는 내부 JavaScriptSerializer 인스턴스에만 적용됩니다. ( MSDN : ScriptingJsonSerializationSection.MaxJsonLength 속성 )

기본적으로 "내부" JavaScriptSerializer는maxJsonLength 는 웹 메소드에서 호출 될 때 . JavaScriptSerializer(또는 MVC action-method / Controller를 통한 사용)의 직접적인 사용은 적어도 web.config 의 섹션이 아닌 속성을 존중 하지 않습니다 .maxJsonLengthsystemWebExtensions.scripting.webServices.jsonSerialization

이 문제를 해결하기 위해 Controller 내에서 (또는 실제 어디에서나) 다음을 수행 할 수 있습니다.

var serializer = new JavaScriptSerializer();

// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;

var resultData = new { Value = "foo", Text = "var" };
var result = new ContentResult{
    Content = serializer.Serialize(resultData),
    ContentType = "application/json"
};
return result;

이 답변은 이 asp.net 포럼 답변에 대한 나의 해석입니다 .


5
귀하의 답변은 Json()asp.net mvc에서 작업 결과 방법을 사용할 때 정말 도움이되었습니다 .
— jessegavin

3
그래도 Json ()도 고통 받았다. 감사!
— BritishDeveloper

3
그것은 완전히 정확하고 그 자리를 가치가 있지만, 이것은 최고 답변을지나 읽을 가치가있는 질문 중 하나입니다 :). 감사!
— Nigel

3
MVC4를 사용하는 경우 @fanisch answer도 참조하십시오.
— Beyers

4
직렬화 해제는 어떻습니까? 액션의 모델 바인딩 에서이 오류가 발생했습니다.
— guogangj

345

MVC 4에서는 다음을 수행 할 수 있습니다.

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult()
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior,
        MaxJsonLength = Int32.MaxValue
    };
}

컨트롤러에서.

부가:

지정해야하는 매개 변수에 당황한 사람은 다음과 같이 호출 할 수 있습니다.

Json(
    new {
        field1 = true,
        field2 = "value"
        },
    "application/json",
    Encoding.UTF8,
    JsonRequestBehavior.AllowGet
);

6
위의 MVC 4에서 매력처럼 작동한다는 것을 확인할 수 있습니다. 감사합니다.
— Beyers

9
나도 확인할 수 있습니다. 이 코드를 기본 컨트롤러에 넣는 것이 가장 깔끔한 방법입니다.
— 의회

15
개별 동작 결과에 "MaxJsonLength = Int32.MaxValue"를 추가하면됩니다. 변경이 필요한 컨트롤러 또는 프로젝트 전체가 아닌 경우.
— Hypnovirus

3
이것이 가장 좋은 대답입니다. MaxJsonLength는 컨트롤러마다 구성 할 수 있습니다.
— liang

3
경고 :이 솔루션은 응답의 압축 (요청 된 경우)을 비활성화합니다. 이 필터를 액션에 추가하십시오 : stackoverflow.com/questions/3802107/…
— Gorgi Rankovski

60

web.config 파일에서 json 요청의 최대 길이를 구성 할 수 있습니다.

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

maxJsonLength의 기본값은 102400 입니다. 자세한 내용은 다음 MSDN 페이지를 참조하십시오. http://msdn.microsoft.com/en-us/library/bb763183.aspx


1
이 정수에 저장된 값은 무엇을 나타 냅니까? 이것은 일종의 문자입니까? 정수를 사용하는 이유는 무엇입니까? 감사!
— eaglei22

@ eaglei22 숫자는 maxJsonLength에 사용할 수있는 바이트 수를 나타냅니다. M4N에서 언급했듯이 102400이 기본값 (100KB)입니다.
— Jacob Plonke

이것은 나를 위해 작동하지 않으며 웹 서비스를 사용하지 않았습니다.
— kalai

42

다음과 같이 web.config 설정 후에도 여전히 오류가 발생하는 경우

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

나는 다음과 같이 해결했다.

   public ActionResult/JsonResult getData()
   {
      var jsonResult = Json(superlargedata, JsonRequestBehavior.AllowGet);
      jsonResult.MaxJsonLength = int.MaxValue;
      return jsonResult;
    }

이것이 도움이되기를 바랍니다.


2
web.config에서 maxJsonLength를 설정하는 것은 불필요합니다. jsonResult.MaxJsonLength를 설정하면 충분합니다 (적어도 나를 위해 한 것 (MVC5))
— hormberg

이것은 글로벌 변화가 아니기 때문에 좋습니다.
— rob_james

40

ASP.NET Web Forms 에서이 문제가 발생했습니다. web.config 파일 설정을 완전히 무시했기 때문에 다음과 같이했습니다.

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        serializer.MaxJsonLength = Int32.MaxValue; 

        return serializer.Serialize(response);

물론 이것은 전반적으로 끔찍한 연습입니다. 웹 서비스 호출로이 많은 양의 데이터를 전송하는 경우 다른 접근법을 살펴 봐야합니다.


1
이게 당신을 위해 일했습니까? 이 코드를 어디에 두었습니까?
— user1012598

우리의 문제는 HTML을 허용하는 텍스트 영역이 있었고 사람들이 이미지를 HTML로 포함하여 항목이 매우 커지고 JSON 직렬 변환기가 실패했기 때문입니다. 그것이 가능하다면 사용자가 할 것이라고 생각합니다 ...
— Marko

이 코드를 어디에 두어야하는지 설명해주세요 ... @Flea
— Koray Durudogan

@KorayDurudogan-컨트롤러에 응답을 반환하는 Ajax 메소드에 넣었습니다. 희망이 도움이됩니다!
— Flea

귀하의 답변에 도전하지는 않지만 더 나은 접근 방식이 무엇인지 더 잘 이해하려고 노력하고 있습니다. 사용자의 기준에 따라 결과 크기를 결정하는 쿼리가 있습니다. JsonResult를 반환합니다. Excel 파일을 반환하면 문제가됩니까?
— eaglei22

22

나는 그것을 고쳤다.

//your Json data here
string json_object="........";
JavaScriptSerializer jsJson = new JavaScriptSerializer();
jsJson.MaxJsonLength = 2147483644;
MyClass obj = jsJson.Deserialize<MyClass>(json_object);

잘 작동합니다.


대박! 이것은 글로벌 변화가 아니기 때문에 나에게 효과적이었던 유일한 솔루션입니다. 감사!
— Sealer_05

20

vestigal의 답변을 따라이 솔루션에 도달했습니다.

컨트롤러의 액션에 큰 JSON을 게시해야 할 때 유명한 "JSON JavaScriptSerializer를 사용하여 deserialization을 수행하는 동안 오류가 발생했습니다. 문자열 길이가 maxJsonLength 속성에 설정된 값을 초과합니다. \ r \ n 매개 변수 이름 : 입력 가치 제공자 ".

내가 한 것은 새 ValueProviderFactory, LargeJsonValueProviderFactory를 만들고 GetDeserializedObject 메서드에서 MaxJsonLength = Int32.MaxValue를 설정하는 것입니다.

public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
    IDictionary<string, object> dictionary = value as IDictionary<string, object>;
    if (dictionary != null)
    {
        foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
            LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
    }
    else
    {
        IList list = value as IList;
        if (list != null)
        {
            for (int index = 0; index < list.Count; ++index)
                LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
        }
        else
            backingStore.Add(prefix, value);
    }
}

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

    var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};

    return serializer.DeserializeObject(end);
}

/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
    if (controllerContext == null)
        throw new ArgumentNullException("controllerContext");
    object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
    if (deserializedObject == null)
        return (IValueProvider) null;
    Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
    LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
    return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}

private static string MakeArrayKey(string prefix, int index)
{
    return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}

private static string MakePropertyKey(string prefix, string propertyName)
{
    if (!string.IsNullOrEmpty(prefix))
        return prefix + "." + propertyName;
    return propertyName;
}

private class EntryLimitedDictionary
{
    private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
    private readonly IDictionary<string, object> _innerDictionary;
    private int _itemCount;

    public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
    {
        this._innerDictionary = innerDictionary;
    }

    public void Add(string key, object value)
    {
        if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
            throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
        this._innerDictionary.Add(key, value);
    }

    private static int GetMaximumDepth()
    {
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            int result;
            if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
                return result;
        }
        return 1000;
     }
  }
}

그런 다음 Global.asax.cs의 Application_Start 메소드에서 ValueProviderFactory를 새 것으로 바꾸십시오.

protected void Application_Start()
{
    ...

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

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

    var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
    ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}

1
나는 내가 단지 당신의 대답은 내 일을 저장할 수있는 모든 일을했다, 이것은 대답을 수락해야
— 무하마드와 커스 아지즈

이 코드로 우리는 4메가바이트의 MVC 컨트롤러 최대 json으로 Deserializetion 제한을 무시할 수 있지만, 웹 API를 컨트롤러 최대 json으로 Deserializetion 제한을 재정의 할 수있는 방법이
— 무하마드와 커스 아지즈

17

web.config에 위의 추가를 구현 한 후 "인식 할 수없는 구성 섹션 system.web.extensions"가 표시되는 경우 오류가 발생하면 <ConfigSections>섹션 의 web.config에 추가 하십시오.

            <sectionGroup name="system.web.extensions" type="System.Web.Extensions">
              <sectionGroup name="scripting" type="System.Web.Extensions">
                    <sectionGroup name="webServices" type="System.Web.Extensions">
                          <section name="jsonSerialization" type="System.Web.Extensions"/>
                    </sectionGroup>
              </sectionGroup>
        </sectionGroup>

4
이 문제가 발생했습니다. 그러나이 답변은 효과가 없었습니다. 여기에 설명 된 <sectionGroup> 요소를 추가하는 대신 새로 추가 된 <system.web.extensions> 블록을 </ configuration> 바로 전에 web.config의 맨 끝으로 옮겼습니다. 그런 다음 효과가있었습니다.
— ClearCloud8 2011

이것은 도움이되었지만 내 상황에서 네 번째 줄을 <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/> 에서이 페이지에서 볼 수 있듯이 . forums.asp.net/t/1446510.aspx/1
— Nathan

@ ClearCloud8이 의견이이 페이지에 즉시 퍼지게하십시오.
— Jack Nutkins

11

이 줄을 Controller에 쓸 수 있습니다

json.MaxJsonLength = 2147483644;

이 줄을 쓸 수도 있습니다 web.config

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

`

안전한면에 있으려면 두 가지를 모두 사용하십시오.


10

MVC 의 MiniProfiler 에서이 오류가 발생 하면 특성 MiniProfiler.Settings.MaxJsonResponseSize을 원하는 값 으로 설정하여 값을 늘릴 수 있습니다 . 기본적으로이 도구는 config에 설정된 값을 무시하는 것 같습니다.

MiniProfiler.Settings.MaxJsonResponseSize = 104857600;

의례 mvc- 미니 프로파일 러 .


10

MVC의 Action 메소드에서 MaxJsonLength 속성을 간단히 설정하십시오.

JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
json.MaxJsonLength = int.MaxValue;
return json;

9

Int32.MaxValue로 설정하는 것이 좋습니다.

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;

9

어트리뷰트 매직은 어떻습니까?

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MaxJsonSizeAttribute : ActionFilterAttribute
{
    // Default: 10 MB worth of one byte chars
    private int maxLength = 10 * 1024 * 1024;

    public int MaxLength
    {
        set
        {
            if (value < 0) throw new ArgumentOutOfRangeException("value", "Value must be at least 0.");

            maxLength = value;
        }
        get { return maxLength; }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        JsonResult json = filterContext.Result as JsonResult;
        if (json != null)
        {
            if (maxLength == 0)
            {
                json.MaxJsonLength = int.MaxValue;
            }
            else
            {
                json.MaxJsonLength = maxLength;
            }
        }
    }
}

그런 다음 글로벌 필터 구성을 사용하거나 컨트롤러 / 액션 방식으로이를 적용 할 수 있습니다.


좋은 대답입니다. 사용자 정의 속성을 잘 사용합니다. Max (int.MaxValue) 대신 기본값을 10MB의 1 바이트 문자로 설정 해야하는 특정 (기술적) 이유가 있는지 궁금하십니까?
— Josh

@ 조쉬 아니오, 특별한 이유는 없었습니다.
— Balázs

5

문제는 실제로 17k 레코드를 반환해야하는지 여부입니다. 브라우저에서 모든 데이터를 어떻게 처리 할 계획입니까? 사용자는 어쨌든 17000 행을 스크롤하지 않을 것입니다.

더 좋은 방법은 "최고 몇 개의"레코드 만 검색하고 필요에 따라 더 많이로드하는 것입니다.


1
json의 기본 목록은 17k 레코드를 제공합니다. 그러나 자동 완성 기능은 사용자가 입력 한 문자와 일치하는 레코드 만 나열하므로 목록을 더 스크롤 할 필요가 없습니다. 그래서 내가 필요한 것은 17k 데이터를 직렬화 할 수있는 maxJsonLength에 무제한 길이를 설정하는 것입니다.
— Prasad

6
서버 및 클라이언트 측 필터링의 조합을 사용할 수 있습니다. 네트워크 대기 시간은 말할 것도없고 클라이언트 측의 모든 데이터를 필터링하기 어려울 수 있습니다.
— Chetan Sastry

1
이 같은 문제에 얼마 전에 도달 한 후 자동 완성을위한 "onsearch"핸들러를 구현하고 웹 서비스 호출이 "search"텍스트를 전달하고 검색 기준을 필터로 사용하여 Top10 쿼리를 수행하도록 선택했습니다. 이것은 더 많은 개별 ajax 요청을 의미하고, 페이지로드시 전체 목록을 가져 오는 것뿐만 아니라 모든 요청 / 응답이 훨씬 더 작음을 의미했습니다 .
— Mike U

3

다른 사람들이 말한 것처럼 구성에서 설정하거나 직렬 변환기의 개별 인스턴스에서 다음과 같이 설정할 수 있습니다.

var js = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };

3

MVC3에서 JSON을 사용하여 모델 바인더에 대해 자동으로 역 직렬화되고 너무 큰 문제가있는 사람들을 위해 여기 해결책이 있습니다.

  1. JsonValueProviderFactory 클래스의 코드를 MVC3 소스 코드에서 새 클래스로 복사하십시오.
  2. 객체를 역 직렬화하기 전에 최대 JSON 길이를 변경하는 행을 추가하십시오.
  3. JsonValueProviderFactory 클래스를 수정 된 새 클래스로 바꾸십시오.

이 작업을 수행하는 올바른 방향 을 알려준 http://blog.naver.com/techshare/100145191355 및 https://gist.github.com/DalSoft/1588818 에게 감사합니다 . 첫 번째 사이트의 마지막 링크에는 솔루션의 전체 소스 코드가 포함되어 있습니다.


3

View에서 이러한 종류의 문제가 발생하면 아래 방법을 사용하여 해결할 수 있습니다. Iused 이곳까지 Newtonsoft의 패키지를.

@using Newtonsoft.Json
<script type="text/javascript">
    var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
</script>

이것은 Json.NET을 사용하면 최대 길이에 대해 걱정할 필요가 없다는 것을 의미합니까? Json.NET에 최대 길이를 설정하는 방법이 없다고 생각하므로 상자에서 즉시 작동하기를 바랍니다.
— kimbaudi

1
훌륭한 답변 감사합니다! 이것은 객체를로드하려고 할 때도 작동했습니다.
— user1299379

3
 JsonResult result = Json(r);
 result.MaxJsonLength = Int32.MaxValue;
 result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 return result;

2

"무제한"값이없는 것 같습니다. 기본값은 2097152 자이며 4MB의 유니 코드 문자열 데이터에 해당합니다.

이미 살펴본 바와 같이 17,000 개의 레코드가 브라우저에서 잘 사용되지 않습니다. 집계보기를 제공하는 경우 서버에서 집계를 수행하고 브라우저에서 요약 만 전송하는 것이 훨씬 더 효율적일 수 있습니다. 예를 들어, 파일 시스템 브로워를 고려하면 트리의 맨 위쪽 만보고 드릴 다운 할 때 추가 요청을 보냅니다. 각 요청에서 반환 된 레코드 수는 비교적 적습니다. 트리보기 프리젠 테이션은 큰 결과 세트에 적합합니다.


3
기괴하게 코드의 기본값 (new JavaScriptSerializer ()). MaxJsonLength는 2097152 바이트이지만 웹 서비스 ResponseFormatJson은 명시 적으로 설정하지 않는 한 102400 바이트입니다.
— rob

2

이것에 부딪쳤다. 6,000 개가 넘는 레코드를 받고 있습니다. 방금 페이징을하기로 결정했습니다. 에서처럼 MVC JsonResult 엔드 포인트에서 페이지 번호를 수락합니다. 기본적으로 0으로 설정되므로 다음과 같이 필요하지 않습니다.

public JsonResult MyObjects(int pageNumber = 0)

그런 다음 말하는 대신

return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);

내가 말하다:

return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);

매우 간단합니다. 그런 다음 JavaScript 대신 다음을 수행하십시오.

function myAJAXCallback(items) {
    // Do stuff here
}

대신에 나는 말한다 :

var pageNumber = 0;
function myAJAXCallback(items) {
    if(items.length == 1000)
        // Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
    }
    // Do stuff here
}

그리고 처음부터 기록한 내용에 기록을 첨부하십시오. 또는 모든 통화가 끝날 때까지 기다렸다가 결과를 함께 모으십시오.


2

이 코드를 추가하는 문제를 해결했습니다.

String confString = HttpContext.Current.Request.ApplicationPath.ToString();
Configuration conf = WebConfigurationManager.OpenWebConfiguration(confString);
ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
section.MaxJsonLength = 6553600;
conf.Save();

이것은 해킹 솔루션처럼 보이지만 흥미로운 접근 방식입니다. 유용한 감사합니다! apsnet mvc 5 컨트롤러의 경우 네임 스페이스에서 'Current'를 제거해야했습니다. 나는 몇 가지 조정을했다 :string confString = HttpContext.Request.ApplicationPath.ToString(); var conf = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(confString); var section = (System.Web.Configuration.ScriptingJsonSerializationSection)conf.GetSection("system.web.extensions/scripting/webServices/jsonSerialization"); section.MaxJsonLength = int.MaxValue; conf.Save();
— ooXei1sh

2

대체 ASP.NET MVC 5 수정 :

(내 것은 약간의 작은 변화로 위의 MFC 대답과 비슷합니다)

아직 Json.NET으로 변경할 준비가되지 않았으며 요청하는 동안 오류가 발생했습니다. 내 시나리오에서 가장 좋은 방법은 실제 JsonValueProviderFactory프로젝트를 수정하여 글로벌 프로젝트에 수정 사항을 적용하고 global.cs파일을 편집하여 수행 할 수 있다는 것 입니다.

JsonValueProviderConfig.Config(ValueProviderFactories.Factories);

web.config 항목을 추가하십시오.

<add key="aspnet:MaxJsonLength" value="20971520" />

다음 두 클래스를 만듭니다.

public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}

이것은 기본적으로 기본 구현의 정확한 사본 System.Web.Mvc이지만 구성 가능한 web.config appsetting 값이 추가되었습니다 aspnet:MaxJsonLength.

public class CustomJsonValueProviderFactory : ValueProviderFactory
{

    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return null;

        Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);

        return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
        if (string.IsNullOrEmpty(fullStreamString))
            return null;

        var serializer = new JavaScriptSerializer()
        {
            MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
        };
        return serializer.DeserializeObject(fullStreamString);
    }

    private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> strs = value as IDictionary<string, object>;
        if (strs != null)
        {
            foreach (KeyValuePair<string, object> keyValuePair in strs)
                CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);

            return;
        }

        IList lists = value as IList;
        if (lists == null)
        {
            backingStore.Add(prefix, value);
            return;
        }

        for (int i = 0; i < lists.Count; i++)
        {
            CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
        }
    }

    private class EntryLimitedDictionary
    {
        private static int _maximumDepth;

        private readonly IDictionary<string, object> _innerDictionary;

        private int _itemCount;

        static EntryLimitedDictionary()
        {
            _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
        }

        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }

        public void Add(string key, object value)
        {
            int num = this._itemCount + 1;
            this._itemCount = num;
            if (num > _maximumDepth)
            {
                throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
            }
            this._innerDictionary.Add(key, value);
        }
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (string.IsNullOrEmpty(prefix))
        {
            return propertyName;
        }
        return string.Concat(prefix, ".", propertyName);
    }

    private static int GetMaximumDepth()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }

    private static int GetMaxJsonLength()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }
}

1
고마워요 ... 감사합니다 @Maxim Gershkovich
— Jasper Manickaraj

1

WebForms UpdatePanel 솔루션 :

Web.config에 설정을 추가하십시오.

<configuration>
  <appSettings>
    <add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
  </appSettings>
</configuration>

https://support.microsoft.com/en-us/kb/981884

ScriptRegistrationManager 클래스에는 다음 코드가 포함됩니다.

// Serialize the attributes to JSON and write them out
JavaScriptSerializer serializer = new JavaScriptSerializer();

// Dev10# 877767 - Allow configurable UpdatePanel script block length
// The default is JavaScriptSerializer.DefaultMaxJsonLength
if (AppSettings.UpdatePanelMaxScriptLength > 0) {
    serializer.MaxJsonLength = AppSettings.UpdatePanelMaxScriptLength;
}  

string attrText = serializer.Serialize(attrs);

1

서버 측 변경은 필요하지 않습니다. web.config 파일로만 수정할 수 있습니다 . 이것은 도움이되었습니다. 이것을 시도

<appSettings>
 <add key="aspnet:MaxJsonDeserializerMembers" value="2147483647" />
<add key="aspnet:UpdatePanelMaxScriptLength" value="2147483647" />
</appSettings>  

and   

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


0

사용하다 lib\Newtonsoft.Json.dll

public string serializeObj(dynamic json) {        
    return JsonConvert.SerializeObject(json);
}

0

ASP.NET MVC 수정 : 문제를 일으키는 특정 작업에 대해서만 수정하려면 다음과 같이 코드를 작성하십시오.

public JsonResult GetBigJson()
{
    var someBigObject = GetBigObject();
    return Json(someBigObject);
}

당신은 이것으로 바꿀 수 있습니다 :

public JsonResult GetBigJson()
{
    var someBigObject = GetBigObject();
    return new JsonResult()
    {
        Data = someBigObject,
        JsonRequestBehavior = JsonRequestBehavior.DenyGet,
        MaxJsonLength = int.MaxValue
    };
}

기능이 동일해야합니다. 더 큰 JSON을 응답으로 반환 할 수 있습니다.


ASP.NET MVC 소스 코드를 기반으로 한 설명 : Controller.JsonASP.NET MVC 소스 코드 에서 수행되는 메소드를 확인할 수 있습니다.

protected internal JsonResult Json(object data)
{
    return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}

다른 Controller.Json방법을 호출합니다 .

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior
    };
}

전달 된 곳 contentType과 contentEncoding객체는 null입니다. 따라서 기본적으로 return Json(object)컨트롤러에서 호출하는 것은 호출하는 것과 같습니다 return new JsonResult { Data = object, JsonRequestBehavior = sonRequestBehavior.DenyGet }. 두 번째 양식을 사용하고 매개 변수화 할 수 있습니다 JsonResult.

MaxJsonLength속성 을 설정하면 어떻게됩니까 (기본적으로 null 임)? 그건 아래로 통과 에 JavaScriptSerializer.MaxJsonLength재산과 그 다음 JavaScriptSerializer.Serialize방법은 전화 :

JavaScriptSerializer serializer = new JavaScriptSerializer();
if (MaxJsonLength.HasValue)
{
    serializer.MaxJsonLength = MaxJsonLength.Value;
}

if (RecursionLimit.HasValue)
{
    serializer.RecursionLimit = RecursionLimit.Value;
}

response.Write(serializer.Serialize(Data));

당신이하지 세트 할 때 MaxJsonLenght시리얼의 속성을 다음이 소요 기본값 단지 2메가바이트입니다.


-2

이 maxJsonLength 값이 int 인 경우 int 32bit / 64bit / 16bit ...의 크기는 얼마입니까 .... maxJsonLength로 설정할 수있는 최대 값이 얼마인지 확인하고 싶습니다.

<scripting>
        <webServices>
            <jsonSerialization maxJsonLength="2147483647">
            </jsonSerialization>
        </webServices>
    </scripting>

-4

web.config와 관련이 없어도 통과 목록의 catch 값 중에 짧은 속성을 사용할 수 있습니다. 예를 들어

public class BookModel
    {
        public decimal id { get; set; }  // 1 

        public string BN { get; set; } // 2 Book Name

        public string BC { get; set; } // 3 Bar Code Number

        public string BE { get; set; } // 4 Edition Name

        public string BAL { get; set; } // 5 Academic Level

        public string BCAT { get; set; } // 6 Category
}

여기에 BC = barcode BE = book edition 등과 같은 짧은 비율을 사용합니다.


대량의 데이터가 속성 값에있는 경우에는 도움이되지 않습니다.
— Window
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.