Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to handle custom API response/output format in the best possible way

$
0
0

I'd like to create custom JSON format, that would wrap the response in data and would return Content-Type like "vnd.myapi+json" ? Currently I have created like a wrapper classes that I return in my controllers but it would be nicer if that would be handled under the hood:

[HttpGet("{id}")]
public async Task<ActionResult<ApiResult<Bike>>> GetByIdAsync(int id)
{
    var bike = _dbContext.AsNoTracking().SingleOrDefault(e => e.Id == id);
    if (bike == null)
    {
        return NotFound();
    }
    return new ApiResult<Bike>(bike);
}

where result looks like:

public class ApiResult<TValue>
{
    [JsonProperty("data")]
    public TValue Value { get; set; }
    [JsonExtensionData]
    public Dictionary<string, object> Metadata { get; } = new Dictionary<string, object>();
    public ApiResult(TValue value)
    {
        Value = value;
    }
}

Could you recommend any good way to handle this?

I'd like to respond with something like

{"data": { ... },"pagination": { ... },"someothermetadata": { ... }
}

where the pagination would be added only for collections, but still I would probably have to handle it in my controller logic to generate links to next and previous pages.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>