简体   繁体   中英

How to define output parameter in Task<IActionResult>

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;

You return an IActionResult in this method but your return type is 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 == null ? NotFound() : Ok(issue);
    }

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM