如何返回一个对象并将其格式化为json?

时间:2017-05-17 02:42:07

标签: c# .net json asp.net-web-api visual-studio-2017

我尝试使用以下控制器返回JSON对象:

    public async Task<IHttpActionResult> Get(string query)
    {
        var client = new HttpClient(new HttpClientHandler()
        {
            Credentials = new NetworkCredential("myuser", "NotSoSecret#1", "mydomain"),
        });
        var ipAddress = Dns.GetHostAddresses("myorgetc.com").ToList()[0];
        client.BaseAddress = new Uri(string.Format("http://{0}/myorg/api/data/v8.1/", ipAddress.ToString()));

        HttpResponseMessage response = await client.GetAsync(client.BaseAddress +"accounts"+ query);
        object result;

        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsAsync<object>();
            return Ok(result);
        }

        return NotFound();
    }      

它返回了以下异常:

  

此XML文件似乎没有任何关联的样式信息   用它。文档树如下所示。一个错误   已经发生了。类型   &#39; Newtonsoft.Json.Linq.JToken&#39;是一个递归收集数据合同   这是不受支持的。考虑修改。的定义   收集&#39; Newtonsoft.Json.Linq.JToken&#39;删除引用   本身。   System.Runtime.Serialization.InvalidDataContractException     在   System.Runtime.Serialization.DataContract.ValidatePreviousCollectionTypes(类型   collectionType,Type itemType,Dictionary 2 previousCollectionTypes) at System.Runtime.Serialization.DataContract.GetNonDCTypeStableName(Type type, Dictionary 2 previousCollectionTypes)at   System.Runtime.Serialization.DataContract.GetStableName(Type type,   字典2 previousCollectionTypes, Boolean& hasDataContract) at System.Runtime.Serialization.DataContract.GetDefaultStableLocalName(Type type) at System.Runtime.Serialization.DataContract.GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) at System.Runtime.Serialization.DataContract.GetStableName(Type type, Dictionary 2 previousCollectionTypes,Boolean&amp; hasDataContract)at   System.Runtime.Serialization.DataContract.GetCollectionStableName(类型   type,Type itemType,Dictionary`2 previousCollectionTypes,   CollectionDataContractAttribute&安培; collectionContractAttribute)at   System.Runtime.Serialization.CollectionDataContract.CollectionDataContractCriticalHelper..ctor(类型   type,CollectionKind kind,Type itemType,MethodInfo   getEnumeratorMethod,String serializationExceptionMessage,String   deserializationExceptionMessage)at   System.Runtime.Serialization.CollectionDataContract.CollectionDataContractCriticalHelper..ctor(类型   type,CollectionKind kind,Type itemType,MethodInfo   getEnumeratorMethod,MethodInfo addMethod,ConstructorInfo   建设者)   System.Runtime.Serialization.CollectionDataContract..ctor(类型类型,   CollectionKind kind,Type itemType,MethodInfo getEnumeratorMethod,   MethodInfo addMethod,ConstructorInfo构造函数,布尔值   isConstructorCheckRequired)at   System.Runtime.Serialization.CollectionDataContract.IsCollectionOrTryCreate(类型   type,Boolean tryCreate,DataContract&amp; dataContract,Type&amp;物品种类,   Boolean constructorRequired,Boolean skipIfReadOnlyContract)at   System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(的Int32   id,RuntimeTypeHandle typeHandle,Type type)at   System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(的Int32   id,RuntimeTypeHandle typeHandle,Type type)at   System.Runtime.Serialization.DataContractSerializer.GetDataContract(DataContract   declaredTypeContract,Type declaredType,Type objectType)at   System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator   writer,Object graph,DataContractResolver dataContractResolver)at   System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator   writer,Object graph,DataContractResolver dataContractResolver)at   System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator   writer,Object graph,DataContractResolver dataContractResolver)at   System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter的   作家,对象图)   System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(类型   type,Object value,Stream writeStream,HttpContent content)at   System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(类型   type,Object value,Stream writeStream,HttpContent内容,   TransportContext transportContext,CancellationToken   cancellationToken)---从前一个位置到底的堆栈跟踪结束   抛出异常---在   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务   任务)   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   System.Web.Http.Owin.HttpMessageHandlerAdapter.d__13.MoveNext()    

我做错了什么?如何在不知道开发时的确切结构的情况下返回JSON对象?

这是我的创业公司:

public static class Startup
    {
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.

        public static void ConfigureApp(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var container = new UnityContainer();
            container.RegisterType<IAccountsRepository, AccountsRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IAccountService, AccountService>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            appBuilder.UseWebApi(config);
        }


    }

1 个答案:

答案 0 :(得分:1)

将此添加到您的WebApiConfig

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

如果您仍然遇到相同的例外,请查看this answer并查看是否有帮助。

  

事实证明,错误是由于我有一个错误   从NuGet安装的Microsoft Web API包,其中包括   Json.NET。卸载后,它可以正常工作。

     

这可能是你的答案 - 如果没有,看看哪些其他包   你安装了(你不需要)并删除它们。