ProudMonkey

AutoWrapper.Server is now Available!

This space is for rent. Contact me at vmsdurano at gmail dot com.

If you are using AutoWrapper for generating a consistent Http response for your ASP.NET Core API's and you have some server-side applications (.NET Clients) that consume the Response, chances are you are forced to create a schema to properly deserialize the ApiResponse to your Model. The idea behind this project was based on community feedback by dazinator. It occurs to me as well that this might be a common scenario. Big thanks to dazinator!

AutoWrapper.Server is simple library that enables you unwrap the Result property of the AutoWrapper's ApiResponse object in your C# .NET Client code. The goal is to deserialize the Result object directly to your matching Model without having you to create the ApiResponse schema.

Installation

1) Download and Install the latest AutoWrapper.Server from NuGet or via CLI:

PM> Install-Package AutoWrapper.Server -Version 2.0.0  

2) Declare the following namespace in the class where you want to use it.

using AutoWrapper.Server;  

Sample Usage

[HttpGet]
public async Task<IEnumerable<PersonDTO>> Get()  
{
    var client = HttpClientFactory.Create();
    var httpResponse = await client.GetAsync("https://localhost:5001/api/v1/persons");

    IEnumerable<PersonDTO> persons = null;
    if (httpResponse.IsSuccessStatusCode)
    {
        var jsonString = await httpResponse.Content.ReadAsStringAsync();
        persons = Unwrapper.Unwrap<IEnumerable<PersonDTO>>(jsonString);
    }

    return persons;
}

If you are using the [AutoWrapperPropertyMap] to replace the default Result property to something else like Payload, then you can use the following overload method below and pass the matching property:

Unwrapper.Unwrap<IEnumerable<PersonDTO>>(jsonString, "payload");  

Using the UnwrappingResponseHandler

Alternatively you can use the UnwrappingResponseHandler like below:

[HttpGet]
public async Task<IEnumerable<PersonDTO>> Get()  
{
    var client = HttpClientFactory.Create(new UnwrappingResponseHandler());
    var httpResponse = await client.GetAsync("https://localhost:5001/api/v1/persons");

    IEnumerable<PersonDTO> persons = null;
    if (httpResponse.IsSuccessStatusCode)
    {
        var jsonString = await httpResponse.Content.ReadAsStringAsync();
        persons = JsonSerializer.Deserialize<IEnumerable<PersonDTO>>(jsonString);
    }

    return persons;
}

You can also pass the matching property to the handler like in the following:

var client = HttpClientFactory.Create(  
               new UnwrappingResponseHandler("payload"));

That's it. If you used AutoWrapper or if you find this useful, please give it a star to show your support and share it to others.

Thank you!

Buy Me A Coffee