-1

我正在尝试调用 Web API Get 方法来获取数据,但我得到了这个异常::

    {"Message":"An error has occurred.","ExceptionMessage":
"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; 
charset=utf- 8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"Error getting value from 'User' on 'System.Data.Entity.DynamicProxies.tblreferralService_D8499DD69BA2AEEF811721A9A453EE6BD1118C497BB3D8EF9C003F7EDEDC651E'.",
"ExceptionType":"Newtonsoft.Json.JsonSerializationException",
"StackTrace":"   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)\r\n   
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)\r\n   
at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n   
at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.<WriteToStreamAsync>b__c()\r\n   
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)",
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.",
"ExceptionType":"System.ObjectDisposedException",
"StackTrace":"   at System.Data.Objects.ObjectContext.EnsureConnection()\r\n   
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   
at System.Data.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   
at System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)\r\n   
at System.Data.Objects.DataClasses.RelatedEnd.Load()\r\n   
at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n   
at System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n   
at System.Data.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)\r\n   
at System.Data.Entity.DynamicProxies.tblreferralService_D8499DD69BA2AEEF811721A9A453EE6BD1118C497BB3D8EF9C003F7EDEDC651E.get_User()\r\n   
at GetUser(Object )\r\n   
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}

我经历了很多关于同一个异常的问题,但每个问题都有不相关的错误,这就是为什么我无法找出错误的正确原因并且它是修复。我也试过 这个

我将 Angularjs 工厂用于我所有的休息服务,即 Api 控制器。

这是我正在调用的视图和 API 控制器:

<script>
    var demoApp = angular.module('demoApp', []);

    demoApp.config(function ($routeProvider) {
        $routeProvider.when('/', { controller: 'customersController', templateUrl: 'Home/List' })
                      .when('/Edit', { controller: 'customersController', templateUrl: 'Home/Edit' })
                      .otherwise({ redirectTo: '/' });
    });



    demoApp.factory('dataFactory', ['$http', function ($http) {
        var urlBase = '/api/Customer';
        var dataFactory = {};
        dataFactory.getCustomers = function () {
            return $http.get(urlBase);
        };
        dataFactory.getCustomer = function (id) {
            return $http.get(urlBase + '/' + id);
        };
        return dataFactory;
    }]);



    demoApp.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {

        $scope.status;
        $scope.customers;
        getCustomers();

        function getCustomers() {
            dataFactory.getCustomers()
                .success(function (custs) {
                    $scope.customers = custs;
                })
                .error(function (error) {
                    $scope.status = 'Unable to load customer data: ' + error.message;
                });
        }       
    }]);

</script>

API 控制器

 public class CustomerController : ApiController
    {
        //
        // GET: /Customer/
        public HttpResponseMessage Get()
        {
            CustomerService ObjService = new CustomerService();
            var Clients = ObjService.GetClients();
            if (Clients.Count < 1) throw new HttpResponseException(HttpStatusCode.NotFound);
            return Request.CreateResponse<IEnumerable<tblreferralService>>(HttpStatusCode.OK, Clients);
        }

        // GET api/customers/5
        public HttpResponseMessage Get(int id)
        {
            CustomerService ObjService = new CustomerService();
            var Client = ObjService.GetClient(id);
            if (Client == null) throw new HttpResponseException(HttpStatusCode.NotFound);
            return Request.CreateResponse<tblreferralService>(HttpStatusCode.OK, Client);
        }

    }

WEBAPI。配置

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

    }

这就是我在控制台中的内容:: 在此处输入图像描述

请指导我哪里错了。

4

1 回答 1

0

我认为,如果您通过内部异常消息进行处理,这在我看来就是问题所在。您能否找到引发此错误的点。我认为您没有共享与此异常相关的代码。

"ExceptionMessage":"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."

at System.Data.Objects.ObjectContext.EnsureConnection()
于 2014-05-29T12:35:23.957 回答