Where to place the asynchronous request methods following the ASP.NET MVC standards?

3

I've always put it on View Controller, is it the most correct way to do it? I came to doubt because I realized that I am filling my view of asynchronous methods, and I would like to leave it all separated so that I do not get lost.

I've never read anything about good practices from where to put these methods, I would like to know the development pattern related to methods for asynchronous request.

    
asked by anonymous 28.09.2017 / 16:03

1 answer

3

Yes, it is in the Controller of the view that the methods should be requested, whether synchronous or asynchronous.

Following the premise of SoC (Separation of Concerns), its Controller should only contain the requisition methods ( Action/ActionResult ), asynchronism is only a detail of the operation in this case.

The important thing is that methods that actually expose the how service is done, such as database calls and data manipulation, that would configure a layer of access to the database or services to be placed in another project and just called by your web project so it does not get too loaded and confusing.

Adding the suffix Async to the names of asynchronous methods is also good practice.

A clear example of what an asynchronous request method would look like:

public async Task<ActionResult> GetReportsAsync(ReportsViewModel model)
{
    if (ModelState.IsValid)
    {
        // Toda lógica é feita aqui.
        ReportingResult result = await reportingService.GenerateReport(model);
        if (result.Success)
        {
            return Redirect("~/home");
        }
        else
        {
            // View de erro
        }
    }

    return View(model);
}

Clean and clear (and asynchronous). They expose only the necessary and do not leave the code dirty.

Important detail about assíncronismo :

Never use the Task.Run method in controller , asynchronism should start from the inside out, ie in the innermost layers you identify operations that need to be asynchronous, such as database calls, then you can expose the method as Task or async Task and in your Controller call the method with await , same as my example. This is a great asynchronous implementation practice taught by Stephen Cleary.

There is a Microsoft post that talks about asynchronous request, performance, and some of the features offered by ASP.NET MVC: link

    
28.09.2017 / 16:44