Goffo.Http 3.4.0

dotnet add package Goffo.Http --version 3.4.0
                    
NuGet\Install-Package Goffo.Http -Version 3.4.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Goffo.Http" Version="3.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Goffo.Http" Version="3.4.0" />
                    
Directory.Packages.props
<PackageReference Include="Goffo.Http" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Goffo.Http --version 3.4.0
                    
#r "nuget: Goffo.Http, 3.4.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Goffo.Http@3.4.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Goffo.Http&version=3.4.0
                    
Install as a Cake Addin
#tool nuget:?package=Goffo.Http&version=3.4.0
                    
Install as a Cake Tool

READ ME

Goffo.Http

Library that helps with generating urls using HttpClient

How to use

  1. ApiOutput Methods
  2. IApiResponse Methods
Example HTTP Methods using IApiResponse
  1. Create an API Class injecting the HttpClient

  2. Use the CRUD extension Methods for the HttpClient provided which you will pass Request and Response object

    1. ReadAsync
    2. CreateAsync
    3. UpdateAsync
    4. DeleteAsync
  3. These methods should never throw an Exception.
    Instead it catches Exceptions in the ApiResponseException class which you can check and then throw if desired.

  4. You can provide any object for the TErrorResponse of the IApiResponse.
    If you know the Http Content format for non-successfully response you can pass that object Otherwise put in as string and it will return that json as a string (as shown below)


-- Dependency Injection Setup Example

IServiceCollection services = new ServiceCollection;

services.AddHttpClient("MyApiClient", client => client.BaseAddress = new Uri("https://www.MyWebApiSite.com/api/"))
        .AddTypedClient<IEmployeeApi, EmployeeApi>();
services.RegisterGoffoHttp();

-- ============================================================================================================================================================

-- Api Class Example

public class EmployeeApi : IEmployeeApi
{
    private readonly HttpClient _httpClient;

    public EmployeeApi(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<IApiResponse<EmployeeResponse, ApiErrorResponses>> GetEmployeeByIdAsync(EmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}/{request.Id}";
        var response = await _httpClient.ReadAsync<EmployeeResponse>(endpoint, url, cancellationToken);

        return response;
    }

    public async Task<IApiResponse<EmployeeResponses, ApiErrorResponses>> GetEmployeesAsync(CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.ReadAsync<EmployeeResponses>(endpoint, url, cancellationToken);
        return response;
    }

    public async Task<IApiResponse<CreateEmployeeResponse, ApiErrorResponses>> CreateEmployeeAsync(CreateEmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.CreateAsync<CreateEmployeeRequest, CreateEmployeeResponse>(request, endpoint, url, cancellationToken);
        return response;
    }

    public async Task<IApiResponse<UpdateEmployeeResponse, ApiErrorResponses>> UpdateEmployeeAsync(UpdateEmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.UpdateAsync<UpdateEmployeeRequest, UpdateEmployeeResponse>(request, endpoint, url, cancellationToken);
        return response;
    }
    public async Task<IApiResponse<DeleteEmployeeResponse, ApiErrorResponses>> DeleteEmployeeAsync(int id, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}/{id}";
        var response = await _httpClient.DeleteAsync<DeleteEmployeeResponse>(endpoint, url, cancellationToken);
        return response;
    }
}

-- The ApiErrorResponses class is an options instead of implementing your own class for the TErrorResponse.


-- Example Minimal API Endpoint
public static class CreateEmployeeEndpoint
{
    public const string Name = "CreateEmployee";

    public static IEndpointRouteBuilder MapCreateEmployeeEndpoint(this IEndpointRouteBuilder builder)
    {
        builder.MapPost("api/Employees", async ([FromBody] CreateEmployeeRequest request, [FromServices] IEmployeeService service, HttpContext httpContext, CancellationToken cancellationToken) =>
        {
            try
            {
                var employee = request.ToEntity();
                var output = await service.CreateAsync(employee);
                return TypedResults.CreatedAtRoute(output.ToCreateResponse(), Name, new { output.Id });
            }
            catch (ValidationException ex)
            {
                return Results.BadRequest(new ApiErrorResponses
                {
                    Errors = ex.Errors.Select(p => new ApiErrorResponse(p.ErrorMessage)).ToList()
                });
            }
            catch (Exception ex)
            {
                return Results.BadRequest(new ApiErrorResponses
                {
                    Errors = [new ApiErrorResponse(ex.Message)]
                });
            }
        })
        .WithName(Name)
        .Produces<CreateEmployeeResponse>(StatusCodes.Status200OK)
        .Produces<CreateEmployeeResponse>(StatusCodes.Status400BadRequest);

        return builder;
    }
}

-- ApiErrorResponse and ApiErrorResponses are simple class definitions

public class ApiErrorResponse
{
    public ApiErrorResponse()
    {
        
    }

    public ApiErrorResponse(string errorMessage)
    {
        ErrorMessage = errorMessage;
    }
    public string ErrorMessage { get; set; } = string.Empty;
}

public class ApiErrorResponses
{
    public ApiErrorResponses()
    {
        
    }

    public ApiErrorResponses(string errorMessage)
    {
        Errors = new List<ApiErrorResponse> { new ApiErrorResponse(errorMessage) };
    }

    public ApiErrorResponses(IEnumerable<string> errorMessages)
    {
        Errors = errorMessages.Select(errorMessage => new ApiErrorResponse(errorMessage)).ToList();
    }

    public List<ApiErrorResponse> Errors { get; set; } = [];
}

-- There are additional methods for:

        -- IEmptyApiResponse which is used for endpoints that do not need to return a response body.

        -- IDefaultErrorApiResponse which is used for endpoints that do not have a known error response body and will return the HttpContent as a String when HttpClient reponse status code is not successfull.
        
        -- IEmptyDefaultErrorApiResponse which is used for endpoints that do not need to return a response body and do not have a known error response body and will return the HttpContent as a String when HttpClient reponse status code is not successfull.

-- Examples of these methods in use:

    public async Task<IEmptyApiResponse<ApiErrorResponses>> CreateEmployeeAsync(CreateEmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.CreateWithEmptyResponseAsync<CreateEmployeeRequest, ApiErrorResponses>(request, endpoint, url, cancellationToken);
        return response;
    }

    public async Task<IDefaultErrorApiResponse<CreateEmployeeResponse>> CreateEmployeeAsync(CreateEmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.CreateAsync<CreateEmployeeRequest, CreateEmployeeResponse>(request, endpoint, url, cancellationToken);
        return response;
    }

    public async Task<IEmptyDefaultErrorApiResponse> CreateEmployeeAsync(CreateEmployeeRequest request, CancellationToken cancellationToken = default)
    {
        string endpoint = "employees";
        string url = @$"{_httpClient.BaseAddress}{endpoint}";
        var response = await _httpClient.CreateAsync(request, endpoint, url, cancellationToken);
        return response;
    }


-- ======================================================================================================================================================================

-- Console App Example

App app = new();

Console.WriteLine("App is running...");
Console.WriteLine();

var request = new EmployeeRequest(Id: 1);
var response = await app.EmployeeApi.GetEmployeeByIdAsync(request);

if (response.ApiResponseException is not null)
{
    Console.WriteLine($"An error occured: {response.ApiResponseException.Message}");
}

if (response.IsSuccessStatusCode)
{
    Console.WriteLine($"Found Employee: {response.Response!.FirstName} {response.Response.LastName}");
}
else if(response.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
{
    Console.WriteLine($"Employee with Id {request.Id} returned {response.ReasonPhrase}");
}
else
{
    Console.WriteLine($"Unexpected Error: {response.HttpStatusCodeDescription}");
}

Console.WriteLine();
    
Console.ReadLine();

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.4.0 33 3/6/2026
3.3.0 31 3/6/2026
3.2.1 32 3/6/2026
3.2.0 33 3/6/2026
3.1.0 38 3/5/2026
3.0.1 34 3/4/2026
3.0.0 33 3/4/2026
2.0.0 297 11/21/2025
1.5.0 165 7/31/2025
1.4.0 150 7/31/2025
1.3.0 153 7/31/2025
1.2.0 151 7/31/2025
1.1.0 163 7/31/2025
1.0.0 481 3/24/2025

Added new methods for empty response output and/or using the default error response which is string