Home > Software engineering >  what to return when return type is Task<IactionResult> in .netcore
what to return when return type is Task<IactionResult> in .netcore

Time:09-22

Im really confused in .Netcore what normally should return to a queue(messagebroker),I have a class

 public  Task<IActionResult> GetMerchantPlatform(int  merchantID) {

        try
        {
            var mrchantInfo =  dbContext.MerchantPlatforms.Where(s => s.Id == merchantID);
            return Task.FromResult(mrchantInfo);
        }
        catch (Exception ex)
        {

            throw ex;

         }
      }

it gives me an error :Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Linq.IQueryable<Models.MerchantPlatform>>' to 'System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>'

when should i return Iactionresult?and when should i return the class?and why im getting the above error?

CodePudding user response:

By using the ControllerBase class you have to return an IActionResult or a Task<IActionResult>. There are plenty of pre-defined result objects available, which you can choose from, cause the result consist of multiple information that has to be defined by you. First is the HTTP status code that should be returned and depending on that you potentially have to return a body and/or some header entries.

If your method is within a ControllerBase class, there are already some helper methods within this class like Ok(), BadRequest(), Forbid(), NoContent(), NotFound(), etc. All with several overloads, depending on their usual use case.

So in your case, you probably have to write something like this:

public async Task<IActionResult> GetMerchantPlatform(int  merchantID)
{
    try
    {
        var mrchantInfo = await dbContext.MerchantPlatforms
            .Where(s => s.Id == merchantID)
            .ToListAsync();

        return Ok(mrchantInfo);
    }
    catch (Exception ex)
    {
        return BadRequest(ex);
    }
}

Be aware, that the try/catch is probably not needed in every function. For this purpose you can register your self-written middleware, that can put such a block around each action and act accordingly to your needs. But that's some stuff for another question or a search for

asp core middleware

And if you really want to only return the content in your method, you should consider to use the ApiControllerAttribute.

  • Related