Cant get ASP.NET MVC 6 Controller to return JSON

前端 未结 1 1399
闹比i
闹比i 2020-12-16 18:42

I have an MVC 6 project in which i am using Fiddler to test out Web API. If i take the following controller action which uses EntityFramework 7 to return a List. Then the ht

相关标签:
1条回答
  • 2020-12-16 19:23

    First of all you can use IEnumerable<Order> or IEnumerable<object> as return type instead of JsonResult and return just orderRepository.GetAll(). I recommend you to read the article fr additional information.

    About another error with Bad Gateway. Try to add Newtonsoft.Json in the latest version 8.0.2 to dependencies in package.json and to use use

    services.AddMvc()
        .AddJsonOptions(options => {
            options.SerializerSettings.ReferenceLoopHandling =
                Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
    

    By the way one can reproduce the error "HTTP Error 502.3 - Bad Gateway", which you describes if I just set breakpoint on the return statement of working code and wait long enough. Thus you will see the error "HTTP Error 502.3 - Bad Gateway" very soon on many common errors.

    You can consider to us more helpful serialization options. For example

    services.AddMvc()
        .AddJsonOptions(options => {
            // handle loops correctly
            options.SerializerSettings.ReferenceLoopHandling =
                Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    
            // use standard name conversion of properties
            options.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();
    
            // include $id property in the output
            options.SerializerSettings.PreserveReferencesHandling =
                PreserveReferencesHandling.Objects;
        });
    
    0 讨论(0)
提交回复
热议问题