Skip to content

Impelement Result Pattern in.NET Web API To achieve the unified API response

Notifications You must be signed in to change notification settings

AbdullrhmanElhelw/ResultPattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Unified API Response in .NET Web API With Result Pattern

Introduction

Unified API responses in .NET projects streamline communication between applications, emphasizing consistency and clarity in software development. This readme delineates the advantages and procedural steps involved in implementing unified API responses.

What is a Unified API Response?

A Unified API Response is essentially a standardized format for the responses generated by API endpoints. Regardless of the outcome of the request, the response adheres to a uniform structure, usually enclosed within a Result object. This uniformity enhances clarity and streamlines processing for developers and clients alike.

Implementing Unified API Responses in .NET

Error Class

  • which encapsulates the message.
  • You can easily change from String to Error and vice versa using Implicit Conversion.
public class Error
{
    public Error(string message)
    {
        Message = message;
    }

    public string Message { get; }

    public static Error None => new(string.Empty);

    public static implicit operator Error(string message) => new(message);

    public static implicit operator string(Error error) => error.Message;
}

Result Class

  • will serve as the response object.
public class Result
{
    public Result(bool isSuccess, Error error)
    {
        IsSuccess = isSuccess;
        Error = error;
    }

    public bool IsSuccess { get; }
    public Error Error { get; }

    public static Result Success() => new(true, Error.None);

    public static Result Failure(Error error) => new(false, error);

    public static Result<T> Success<T>(T data) => new(true, Error.None, data);

    public static Result<T> Failure<T>(Error error) => new(false, error, default);
}

Generic Result Class

  • Contains Property Called Data Which Return Result with Data
public class Result<T> : Result
{
    public T? Data { get; }

    public Result(bool isSuccess, Error error, T? data) : base(isSuccess, error)
    {
        Data = data;
    }
}

Match Method

  • Extention Metod based on Result Class To to handle the Success and Failure Cases
public static class ResultExtensions
{
    public static T Match<T>(this Result result,
                             Func<T> onSuccess,
                             Func<Error, T> onFailure)
    {
        return result.IsSuccess ?
               onSuccess() :
               onFailure(result.Error);
    }
}

Read the corresponding Medium article

Releases

No releases published

Packages

No packages published

Languages