10

I have a web-API project and a simple class with a few properties, some are marked <JsonIgnore>.

In my MVC-controller I put Return Json(instanceOfMyClass, JsonRequestBehavior.AllowGet). All members are serialized. I put Return Json(Of MyClass)(instanceOfMyClass) in my WEBAPI-controller. Only the members I intend to serialize are present.

How can I ignore these properties independent of the controller that's going to serialize.

2 Answers 2

20

The JsonResult in MVC does not actually use JSON.NET which is why [JsonIgnore] is not working. Instead it uses the JavaScriptSerializer class.

To make the JavaScriptSerializer skip a property, you can you the [ScriptIgnore] attribute on your model property.

An alternative would be to make a custom ActionResult that uses JSON.NET's JsonConvert to serialize the object which would then honor the [JsonIgnore] attribute.

Sign up to request clarification or add additional context in comments.

1 Comment

Any example? :)
2

In case it helps anyone, it didn't seem possible or straightforward to use [ScriptIgnore] in my .net Core app, so I did this:

public IActionResult Index()
{
    Response.ContentType = "text/json";
    return Content(JsonConvert.SerializeObject(instanceOfMyClass));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.