mardi 31 mars 2020

How to the make sure the object returned from MediatR response and Web Api method return type are the same type?

I have this web api method and class

    public async Task<ActionResult<ItemsList<GetJailItemDto>>> GetJailCells([FromBody] JailCellSearchDto jailcellSearchParameters)
    {
        var request = new GetJailCellsQuery()
        {
            JailCellsSearchParameters = jailcellSearchParam
        };
        var response = await _mediator.Send(request).ConfigureAwait(false); //returns Mediatr response object 
        return CreateResponse(response);
    }

    private ObjectResult CreateResponse(MediatRResponse response)
    {
        if (response.IsValid)
        {
            var actionResult = new OkObjectResult(response.ResponseValue);
            return actionResult;
        }
        else
        {
            var objectResult = new ObjectResult(response.ValidationMessages);
            objectResult.StatusCode = 400;
            return objectResult;
        }
    }

public class MediatRResponse
{
    .
    .
    .
    .

    public MediatRResponse(object responseValue)
    {
        Values = responseValue;
        Errors = new List<ErrorItems>();
    }

    public object Values { get; protected set; } //stores items from DB


    public IList<ErrorItems> lErrorItems{ get; set; }

    public bool IsValid
    {
        get
        {
            return !lErrorItems.Any();
        }
    }
}

public class ListItems<T>
{
    public IEnumerable<T> Items { get; set; } //Stores Items
    public int Rows { get; set; }
}

This runs successfully but we noticed that, when we replaced the return type of the api from

async Task<ActionResult<ItemsList<GetJailItemDto>>>

to

async Task<ActionResult<int>>

it still works and returns items

Is it possible to have this type safe given that mediatr determines response type on runtime?

I have given up on this solution, so I have tried another appproach

The solution that I have thought of is to use reflection to get the return type of the executing method which is

Task<ActionResult<ItemsList<GetJailItemDto>>> or Task<ActionResult<int>

and compare it with the type of response.Values which should return

ItemsList<GetJailItemDto>>

and compare it to generic return type of the method.

If method return type is

async Task<ActionResult<ItemsList<GetJailItemDto>>>

then return 200 OK

if method return type

async Task<ActionResult<int>>

then return bad request

This is my attempt to code this

var method = MethodBase.GetCurrentMethod();

var returnType = ((MethodInfo)method).ReturnType; //get return type of executing method

for some reason it returns System.Void instead, probably because its async.

is there a way to get

ItemsList<GetJailItemDto> type 

from

Task<ActionResult<ItemsList<GetJailItemDto>>>

Personally I prefer the typesafe solution but resorted to reflection out of desperation need help.





Aucun commentaire:

Enregistrer un commentaire