joukevandermaas / saule

JSON API library for ASP.Net Web API 2.
https://joukevandermaas.github.io/saule
MIT License
76 stars 37 forks source link

Disable attributes from controller? #220

Closed bracke closed 5 years ago

bracke commented 5 years ago

Hi

I have controller which returns emails, including the body of the email. Since this attribute is very large I would like it to not return that field when fetching a list of emails. On the other hand I definitely want i it to return that field when fetching a single email.

Is there any way i can achieve this behavior with Saule. As an alternative, is there a way I can disable Saule for a specific method in a controller?

Kind regards Bent Bracke

joukevandermaas commented 5 years ago

The way to do this in saule, is to create two ApiResource implementations. They can of course be subclasses of each other.

Example:

public class EmailResource : ApiResource
{
    public EmailResource()
    {
        Attribute("Subject");
        Attribute("To");
        Attribute("CC");
    }
}

public class EmailWithBodyResource : EmailResource
{
    public EmailWithApiResource()
    {
        OfType("Email");
        Attribute("Body");
    }
}

Then on the list endpoint, you use [ReturnsResource(typeof(EmailApiResource))]. On the single-item endpoint you use [ReturnsResource(typeof(EmailWithBodyResource))]. Even when both return the same model type, this will change the API response to include the attribute in one response, and not the other.

bracke commented 5 years ago

Thats awesome! Thank you!