locked
Error RRS feed

  • Question

  • User1979860870 posted

    Hi

      I am getting below error

        public partial class Employee
        {
            public Employee()
            {
                CreatedOn = DateTime.Now;
            }
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string Gender { get; set; }
            public Nullable<int> Salary { get; set; }
            public Nullable<int> DepartmentId { get; set; }
            public string Active { get; set; }
    
            [Display(Name = "Created On")]
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
            public Nullable<System.DateTime> CreatedOn { get; set; }
            public Nullable<System.DateTime> UpdatedOn { get; set; }
    
            public virtual Department Department { get; set; }
        }

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
    
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }



    public class EmployeesController : ApiController
        {

    private Cnn db = new Cnn();

    public IEnumerable<Employee> GetEmployees()
            {
                var result = db.Employees.ToList();
                return result;

            }

    }

    <Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage>
    <ExceptionType>System.InvalidOperationException</ExceptionType>
    <StackTrace/>
    <InnerException>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>Type 'System.Data.Entity.DynamicProxies.Employee_94FC830560691407DBFFF7B0886725AEAA5615CD63EA634B65E0C7A525B8478F' with data contract name 'Employee_94FC830560691407DBFFF7B0886725AEAA5615CD63EA634B65E0C7A525B8478F:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.</ExceptionMessage>
    <ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType>
    <StackTrace> at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteArrayOfEmployeeToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) 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 writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()</StackTrace>
    </InnerException>
    </Error>

    Thanks

    Monday, February 15, 2021 4:43 AM

Answers

  • User475983607 posted

    The linked tutorial is performing CRUD operation on a a single table and returning the entity.   Your design uses virtual navigation properties. 

    In Entity Framework the virtual navigation properties create a proxy for lazy loading.  Your design tries to return the entire entity which includes the proxy which is causing the serialization exception.  As recommend many time now across many of your threads, follow a DTO pattern.  See the link I proved above and/or do a Google search for many examples of the DTO pattern.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 17, 2021 11:53 AM

All replies

  • User475983607 posted

    The error and design problem was explained your other threads.  It seems you did not follow the advice.  Again, the error is due to returning an Entity Type from Web API.   There's more to an entity than just the properties.    You'll need to fix your design and return what's called a DTO or a POCO.  Basically, populate another class using the entity and return the new class not the Entity.

    Also, you can lookup the error on the internet to find the same advice.

    Monday, February 15, 2021 12:42 PM
  • User1979860870 posted

    HI mgebhard

      Wht i should change

    Thanks

    Monday, February 15, 2021 2:01 PM
  • User475983607 posted

    Wht i should change

    I explained what to do in this thread and you others.  Basic programming patterns are also covered in every beginning level tutorial.  I'm not sure sure how to help you as you do have not listened to any of the advice given so far. 

    The solution is to stop returning Entities from Web API.  Return a model that you create.  This is also called a DTO or a POCO.  This is not a hidden or unknow programming pattern.  

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    Monday, February 15, 2021 2:20 PM
  • User1979860870 posted

    Hi

       i am following this link but still i am getting same error - https://www.c-sharpcorner.com/article/crud-Asp-Net-web-api-with-entity-framework-in-Asp-Net-mvc/

    public IQueryable<Employee> GetEmployees()
            {
                return db.Employees;
            }



    --------- On below code also same error

    public IHttpActionResult GetEmployees()
            {
                var results = db.Employees.ToList();
                return Ok(results);
            }

    Thanks

    Wednesday, February 17, 2021 8:51 AM
  • User475983607 posted

    The linked tutorial is performing CRUD operation on a a single table and returning the entity.   Your design uses virtual navigation properties. 

    In Entity Framework the virtual navigation properties create a proxy for lazy loading.  Your design tries to return the entire entity which includes the proxy which is causing the serialization exception.  As recommend many time now across many of your threads, follow a DTO pattern.  See the link I proved above and/or do a Google search for many examples of the DTO pattern.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 17, 2021 11:53 AM
  • User379720387 posted

    i think what mgebhard means is that you create a Model like so:

    public class EmployeeData
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string Gender { get; set; }
            public Nullable<int> Salary { get; set; }
            public Nullable<int> DepartmentId { get; set; }
            public string Active { get; set; }
        }

     

    Wednesday, February 17, 2021 3:00 PM
  • User1979860870 posted

    Hi Mgebhard

       With below code i am getting above error

    public IHttpActionResult GetEmployees()
            {
                var results = (from d in db.Employees
                               join f in db.Departments
                               on d.DepartmentId equals f.ID
                               select new
                               {
                                   Id = d.ID,
                                   Name = d.Name,
                                   Department = f.Description
                               }).ToList();
                return Ok(results);
            }

    After writing the below code in WebApiConfig then it is showing data correctlt in Json format. Why do i need to write these line

     config.Formatters.Remove(config.Formatters.XmlFormatter);
                config.Formatters.Add(config.Formatters.JsonFormatter);
                config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

    Thanks

    Thursday, February 18, 2021 6:16 AM
  • User475983607 posted

    jagjit saini

     With below code i am getting above error

    What error?

    jagjit saini

    After writing the below code in WebApiConfig then it is showing data correctlt in Json format. Why do i need to write these line

    Web API 2.0 returns the format request by the client called content negotiation.  XML is a default data format.  But you removed the XML formatter so XML is left.

    The links that I have provided in this post as well as you many others cover this information.  

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation

    https://docs.microsoft.com/en-us/aspnet/web-api/

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

    Thursday, February 18, 2021 11:18 AM