Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

asp.net core webapi - Using MediatR in Web API - How do you handle different status codes

I am using (and learning how to use) MediatR and am trying to use it in my Web API. My question is, assuming that the goal of the 'controller' is to look like the following where you simply send off the message:

[ApiController]
public class List : ControllerBase
{
    private readonly IMediator mediator;

    public List( IMediator mediator )
    {
        this.mediator = mediator;
    }

    [HttpGet( "/calc-engines" )]
    public async Task<ActionResult<CalcEngine[]>> HandleAsync(
        [FromQuery] Query query,
        CancellationToken cancellationToken = default ) => await mediator.Send( query, cancellationToken );

What is the best practice to handle different status codes based on item not found, forbidden, etc.?

Do you have your handler return a complex type with a Payload (the requested item) along with an HttpStatus and then examine the result in the action and return appropriately? Throw exceptions and catch in the action (or a filter) and set status based on exception type?

Update: This is the best I could come up with, but wondering if there is something better.

public class ApiResult<T>
{
    private ApiResult( HttpStatusCode failureStatus ) => FailureStatus = failureStatus;
    private ApiResult( T payload ) => Payload = payload;

    public T Payload { get; }
    public HttpStatusCode? FailureStatus { get; }
    public bool IsSuccess => FailureStatus == null;

    public static ApiResult<T> Fail( HttpStatusCode failureStatus ) => new ApiResult<T>( failureStatus );
    public static ApiResult<T> Success( T paylooad ) => new ApiResult<T>( paylooad );

    public static implicit operator bool( ApiResult<T> result ) => result.IsSuccess;
}

Then handler looks something like this:

public async Task<ApiResult<SomeType>> Handle( TRequest message, CancellationToken token )
{
    if ( badValidation )
    {
        return ApiResult<SomeType>.Fail( HttpStatusCode.BadRequest );
    }

    // do work...

    return ApiResult<SomeType>.Success( someResult );
}

And action looks something like this:

public async Task<ActionResult<ApiResult<SomeType>>> HandleAsync(
    [FromQuery] Query query,
    CancellationToken cancellationToken = default )
{
    var result = await mediator.Send( query, cancellationToken );

    if ( result ) return result;

    return StatusCode( (int)result.FailureStatus );
}

question from:https://stackoverflow.com/questions/65942801/using-mediatr-in-web-api-how-do-you-handle-different-status-codes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 public class ErrorHandler:Exception
{
    public HttpStatusCode Codigo { get; set; }
    public object Error { get; set; }

    public ErrorHandler(HttpStatusCode Code, object Err)
    {
        this.Codigo = Code;
        this.Error = Err;
    }
}

i work with mediatr and i handle exceptions with this code. usage example bellow

 var Comment = await contexto.TComentario.FindAsync(request.CommentId);
            
            if (Comment == null)
                throw new ManejadorErr.ErrorHandler(System.Net.HttpStatusCode.NotFound, new { Message = "comment no could be found" });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...