Goffo.Http
3.4.0
dotnet add package Goffo.Http --version 3.4.0
NuGet\Install-Package Goffo.Http -Version 3.4.0
<PackageReference Include="Goffo.Http" Version="3.4.0" />
<PackageVersion Include="Goffo.Http" Version="3.4.0" />
<PackageReference Include="Goffo.Http" />
paket add Goffo.Http --version 3.4.0
#r "nuget: Goffo.Http, 3.4.0"
#:package Goffo.Http@3.4.0
#addin nuget:?package=Goffo.Http&version=3.4.0
#tool nuget:?package=Goffo.Http&version=3.4.0
READ ME
Goffo.Http
Library that helps with generating urls using HttpClient
How to use
- ApiOutput Methods
- IApiResponse Methods
Example HTTP Methods using IApiResponse
Create an API Class injecting the HttpClient
Use the CRUD extension Methods for the HttpClient provided which you will pass Request and Response object
- ReadAsync
- CreateAsync
- UpdateAsync
- DeleteAsync
These methods should never throw an Exception.
Instead it catches Exceptions in the ApiResponseException class which you can check and then throw if desired.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 | Versions 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. |
-
net10.0
- Microsoft.AspNetCore.WebUtilities (>= 10.0.3)
- Microsoft.Extensions.Http (>= 10.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Added new methods for empty response output and/or using the default error response which is string