Answer the question
In order to leave comments, you need to log in
Using ScriptIgnoreAttribute in .net Standard 2.0, what's the alternative?
Hello.
In a web application based on the .net Framework 4.7.2. in the Action of the controller, to return the model to the client in JSON format, the following code is used:
return Json(data, JsonRequestBehavior.AllowGet);
In order to avoid problems with cyclic references during serialization, the .net Framework has the ScriptIgnoreAttribute attribute, which can be used to mark the properties of the model class so that they are not serialized.
But I had a problem with this: my model is defined in the .net Standard 2.0 assembly, and I did not find such an attribute in it.
I tried using the Newtonsoft.Json.JsonIgnoreAttribute attribute instead, but it's not respected by the standard serializer.
I tried changing the controller code to
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
but this required changing the client javascript (in this case the content was a string that needed to be parsed on the client into an object).
In general, this approach of mine required a large amount of work, which I would like to avoid.
Question: is it possible to use some attribute that is in the .net Standard and which is an analogue of ScriptIgnore for the standard serializer from the .net Framework?
Thank you for your attention.
Answer the question
In order to leave comments, you need to log in
1. return Json(data, JsonRequestBehavior.AllowGet);
this is a wrapper over JavaScriptSerializer, to which you can set custom converters, and ignore the field there.
2. return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
should also work if the return content type is set to json.
F12 to see what comes to the client.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question