-
Notifications
You must be signed in to change notification settings - Fork 0
1 Create an HTTP API
The bulk of this package is targeted to help create API clients. On the server side, the packages only provide a light wrapper around standard .NET Core HTTP API functionality, namely by providing a standard base class and response extension method. The packages are primarily targeted at JSON based APIs, but is extensible to accommodate others.
Begin with a new or existing .NET Core web project (.NET 6) as you normally would.
Install the Confidia.ApiAbstractions.Http.Server nuget package.
Object payloads returned from Controllers should be changed to inherit from HttpApiMessageBase and the IActionResult that is returned should be calculated by this.HttpApiResult(message) where message has been created by the methods found in ApiMessageBuilder:
CreateSuccess(Action<HttpApiMessageBase>? alter = null)CreateFailure(HttpStatusCode statusCode, string? message, dynamic errorCode, Action<HttpApiMessageBase>? alter = null)CreateSuccess<TMessage>(Action<TMessage>? alter = null)CreateFailure<TMessage>(HttpStatusCode statusCode, string? message, dynamic errorCode, Action<TMessage>? alter = null)
The dynamic errorCode you pass here must be an enum of your choosing.
Simplified example below (normally you would want the logic of creating the response message to be in a service class not in the controller):
public enum ApiError
{
SomethingWrong = 10
}
[HttpGet("fail")]
public IActionResult Fail()
{
var message = HttpApiMessageBuilder.CreateFailure(HttpStatusCode.PaymentRequired, "Payment required", ApiError.SomethingWrong);
return this.HttpApiResult(message);
}
[HttpGet("success")]
public IActionResult Success()
{
var message = HttpApiMessageBuilder.CreateSuccess();
return this.HttpApiResult(message);
}
Note the failure model requires an enum to be sent through for the error code. This ensures your API client will have machine readable reasons for failed requests and will be able to act accordingly.