ASP.NET Web-API does not serialize readonly property

I migrated the API method from the standard MVC action to the new beta version of asp.net web-API, and suddenly the read only property no longer serializes (both return JSON). Is this expected behavior?

Edit: added code sample

I have both Newtonsoft.Json 4.0.8 and System.Json 4.0 referenced by nuget packages

public IQueryable<Car> Gets() { return _carRepository.GetCars(); } public class Car { public IEnumerable<Photo> Photos { get { return _photos; } } public string PreviewImageUrl // No longer serialized { get { var mainImage = Photos.FirstOrDefault(o => o.IsMainPreview) Photos.FirstOrDefault(); return mainImage != null ? mainImage.Url : (string.Empty); } } } } 
+6
source share
2 answers

JsonMediaTypeFormatter , which comes with the beta version, uses a serializer that does not support read-only properties (as they will not be rounded correctly). We plan to consider this for the following real ones.

At the same time, you can use the custom JSON implementation of MediaTypeFormatter , which uses Json.NET (there is one available here ) instead of the built-in formatter.

Update: Also check out the Henrik block on enabling JSON.NET formatting: http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web- api.aspx p>

+10
source

I do not know if this is the expected behavior or not. I would say that this is expected for input parameters (because you cannot set their values), but not for output parameters. Therefore, I would say that this is an error for the output parameter. And here is an example illustrating the problem:

Model:

 public class Product { public Product() { Prop1 = "prop1 value"; Prop2 = "prop2 value"; Prop3 = "prop3 value"; } public string Prop1 { get; set; } [ReadOnly(true)] public string Prop2 { get; set; } public string Prop3 { get; protected set; } } 

Controller:

 public class ProductsController : ApiController { public Product Get(int id) { return new Product(); } } 

Inquiry:

 api/products/5 

Result:

 {"Prop1":"prop1 value","Prop2":"prop2 value"} 

So, if the property does not have a public setter, it does not serialize, which does not seem normal, since the Product class is used as output in this case.

I would suggest opening a connection ticket so that Microsoft can fix it before the release, or at least say that it is by design.

+4
source

Source: https://habr.com/ru/post/908994/


All Articles