对Web机制进行故障排除。

时间:2014-05-29 06:16:15

标签: angularjs asp.net-mvc-4 asp.net-web-api angularjs-factory

我正在尝试调用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)"}}}

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

我正在将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 }
            );
        }

    }

这就是我在控制台中所拥有的:: enter image description here

请指导我错误的地方。

1 个答案:

答案 0 :(得分: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()