2013-07-03 3 views
1

컨트롤러를 만들어 JSON 형식의 개체를 반환합니다. Newtonsoft.Json 라이브러리를 사용하고 싶습니다. 나는 아약스 나 브라우저 URL에서 RetrieveTestClassJson를 호출 할 때JSON.NET MVC 4 WebApi

[HttpGet] 
[ActionName("RetrieveTestClassJson")] 
public ActionResult RetrieveTestClassJson(int id) 
{ 
    TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component }; 
    JsonNetResult jsonNetResult = new JsonNetResult(); 
    jsonNetResult.Formatting = Formatting.Indented; 
    jsonNetResult.ContentType = "application/json"; 
    jsonNetResult.ContentEncoding = Encoding.Unicode; 
    jsonNetResult.Data = testThing; 
    return jsonNetResult; 
} 

[HttpGet] 
[ActionName("RetrieveTestClassCase2")] 
public TestThing RetrieveTestClassCase2(int id) 
{ 
    TestThing testThing = new TestThing() { Name = "LPL.22.334", Type = TypeTest.Component }; 
    return testThing; 
} 

내가 얻을 : 내가 RetrieveTestClassCase2를 호출 할 때

{"ContentEncoding":{"isThrowException":false,"bigEndian":false,"byteOrderMark":true,"m_codePage":1200,"dataItem":null,"encoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"decoderFallback":{"strDefault":"�","bIsMicrosoftBestFitFallback":false},"m_isReadOnly":true},"ContentType":"application/json","Data":{"Name":"LPL.22.334"},"SerializerSettings":{"ReferenceLoopHandling":0,"MissingMemberHandling":0,"ObjectCreationHandling":0,"NullValueHandling":0,"DefaultValueHandling":0,"Converters":[{"CamelCaseText":true,"CanRead":true,"CanWrite":true}],"PreserveReferencesHandling":0,"TypeNameHandling":0,"TypeNameAssemblyFormat":0,"ConstructorHandling":0,"ContractResolver":null,"ReferenceResolver":null,"TraceWriter":null,"Binder":null,"Error":null,"Context":{"m_additionalContext":null,"m_state":0},"DateFormatString":"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK","MaxDepth":null,"Formatting":0,"DateFormatHandling":0,"DateTimeZoneHandling":3,"DateParseHandling":1,"FloatFormatHandling":0,"FloatParseHandling":0,"StringEscapeHandling":0,"Culture":"(Default)","CheckAdditionalContent":false},"Formatting":1} 

내가 정상 JSON 포맷을 얻을 나는 두 가지 방법을 만들었습니다. 내가 지금은 테스트 목적으로 XML 처리기를 제거 :

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); 
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); 

내가 무슨 일이 일어나고 있는지의 의아해입니다.

답변

6

WebApi는 이미 파이프 라인에있는 Json 시리얼 라이저 (http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization)를 가지고 있으므로 명시 적으로 직렬화하는 방식에서 결과가 두 번 직렬화되는 것으로 보입니다. 두 번째 방법은 json 포맷터를 제거하지 않는 한 원하는 것입니다.

+0

어떻게 내가 JSON 취약점을 방지하기 위해 직렬화 된 문자열에 문자를 추가 할 경우 (http://haacked.com/archive/2008/11/20/anatomy-을하자,/재정의 직렬화 프로세스를 사용자 정의 할 수 있습니다 of-a-subtle-json-vulnerability.aspx)? –

+0

직렬화 프로세스를 사용자 정의하는 몇 가지 예 .. http://tostring.it/2012/07/18/customize-json-result-in-web-api/ – grant

4

아무 것도하지 않을 때 JSON을 반환하는 이유는 MVC가 JSON serialzer에 자체 빌드를 가지고 있기 때문입니다. 이것은

[System.Web.Http.HttpGet] 

때문에하지

[System.Web.Mvc.HttpGet] 

그것은 당신의 데이터로서가 아니라 마크 업으로 보내는 것을 처리합니다. 그것이 JSON으로 객체를 반환하는 이유입니다. 그것은 단지 객체를 전송한다는 것을 알고 있으므로 직렬화합니다. [System.Web.Mvc.HttpGet]에서 동일한 기능을 원한다면 ActionResult 대신 JsonResult를 반환합니다.

var result = new JsonResult(); 
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
result.Data = testThing;