Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Host Web API as empty application #1920


User avatar
0
amayorquin created

Hi,

I'm using the OData sample to create a new Web API application using ABP. I just made some changes.

In the AbpODataDemoWebApiModule.cs, I changed this:

[DependsOn(typeof(AbpWebApiODataModule))]
    public class AbpODataDemoWebApiModule : AbpModule
    {
        public override void PreInitialize()
        {
            var builder = Configuration.Modules.AbpWebApiOData().ODataModelBuilder;

            //Configure your entities here...
            builder.EntitySet<Person>("Persons");

            //TODO: Remove after ABP v0.11.2.0 upgrade
            Configuration.Validation.IgnoredTypes.AddIfNotContains(typeof(Type));
            Configuration.Validation.IgnoredTypes.AddIfNotContains(typeof(Delta));
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
        }
    }

for this:

[DependsOn(typeof(AbpWebApiModule))]
    public class AbpODataDemoWebApiModule : AbpModule
    {
        public override void PreInitialize()
        {
         Configuration.Modules.AbpWebApi().HttpConfiguration.MapHttpAttributeRoutes();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
        }
    }

In the AbpODataDemoWebModule.cs, I just register the Routes, and I created a new class for the routes:

public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
    }

and finally in the controller changed like this:

public class PersonsController : AbpApiController
    {
        private readonly IRepository<Phone> _phoneRepository;
        private readonly IRepository<Person> _personRepository;

        public PersonsController(
            IRepository<Person> personRepository,
            IRepository<Phone> phoneRepository)
  
        {
            _personRepository = personRepository;
            _phoneRepository = phoneRepository;
        }

        [Route("api/Persons/GetPersons")]
        [HttpGet]
        public List<Person> GetPersons()
        {
            var persons = _personRepository.GetAll().ToList();
            return persons;
        }
}

But when I call the method via Postman I'm getting an exception:

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

Here is the complete exception:

{ "message": "An error has occurred.", "exceptionMessage": "The 'ObjectContent1' 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 'Phones' on 'System.Data.Entity.DynamicProxies.Person_E0D0F5809A10CCF521F5B0560F9B6295EB6C1DAE95890460F8EC9161EADC2F00'.", "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, IEnumerable 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, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()", "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.Entity.Core.Objects.ObjectContext.get_Connection()\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(List1 collection, MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass72.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.Person_E0D0F5809A10CCF521F5B0560F9B6295EB6C1DAE95890460F8EC9161EADC2F00.get_Phones()\r\n at GetPhones(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)" } } }


No answer yet!