Home > Mobile >  How to define output parameter in Task<IActionResult>
How to define output parameter in Task<IActionResult>

Time:07-25

I'm switching tech stacks so I'm a bit confused here. This function should return an object

public async Task<IActionResult> Search(CoinModel Coin)
{
    var date = Coin.tracking_date.ToLocalTime().ToString("dd/MM/yyyy");
    var dateformat = DateTime.Parse(System.Web.HttpUtility.UrlDecode(date   " 00:00:00.0000000"));
    var issue = await _db.Coins.SingleOrDefaultAsync(c => c.coin == Coin.coin.ToUpper() && c.tracking_date == dateformat);
    return issue == null ? NotFound() : Ok(issue);
}

But I can't seem to access the result like this

var search = await Search(Coin);
return search.id;

CodePudding user response:

I would suggest a helper method.

private async Task<Coin> SearchAsync(CoinModel Coin)
{
    var date = Coin.tracking_date.ToLocalTime().ToString("dd/MM/yyyy");
    var dateformat = DateTime.Parse(System.Web.HttpUtility.UrlDecode(date   " 00:00:00.0000000"));
    var issue = await _db.Coins.SingleOrDefaultAsync(c => c.coin == Coin.coin.ToUpper() && c.tracking_date == dateformat);
    return issue == null ? NotFound() : Ok(issue);
}


public async Task<IActionResult> Search(CoinModel coin)
{
    var issue = await SearchAsync(coin);
    return issue == null ? NotFound() : Ok(issue);
}

Btw. In C# the convetion is to start argument with a common letter, so CoinModel coin, not CoinModel Coin.

CodePudding user response:

You return an IActionResult in this method but your goal is to return a Coin (Entity). You should change the return type of your method. I assume that class name of coin entity is 'Coin'

    [NonAction]
    public async Task<Coin> Search(CoinModel Coin)
    {
        var date = Coin.tracking_date.ToLocalTime().ToString("dd/MM/yyyy");
        var dateformat = DateTime.Parse(System.Web.HttpUtility.UrlDecode(date   " 00:00:00.0000000"));
        var issue = await _db.Coins.SingleOrDefaultAsync(c => c.coin == Coin.coin.ToUpper() && c.tracking_date == dateformat);
        return issue;
    }

By the way, as this method is not an Action method, you can define it using [NonAction]

In addition, You just want to make a search operation on a List. This means this is a 'Business Logic Layer' operation. I believe that we shouldn't do such operations in Controller as Non-Action Methods. In the business logic layer, you can use a 'Result Class' to be able to control exceptions, null returnings and errors. You can look at this link about 'Result Class' => https://josef.codes/my-take-on-the-result-class-in-c-sharp/

  • Related