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

Asked

Viewed 325 times

3

I always put in the View Controller, is the right way to do it? I doubted it because I realized that I am filling my view with asynchronous methods, and I would like to leave it all separate so that I do not get lost.

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

1 answer

3


Yes, it is in the view controller that the methods if request should be, either synchronous or asynchronous.

Following the premise of Soc (Separation of Concerns), his Controller shall contain only the requisition methods (Action/ActionResult), asynchronism is just a detail of how it works in this case.

The important thing is that methods that really expose as the service is done, such as database calls and data manipulation, which would set up an access layer to the database or services be placed in another project and only called by your web project so that it does not get too loaded and confused.

Add suffix Async the names of asynchronous methods is also a good practice.

A clear example of what an asynchronous request method would be:

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). Expose only the necessary and do not leave the dirty code.

Important detail on assíncronismo:

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

Here is a post from Microsoft (in English) that talks about asynchronous request, performance and some of the features offered by ASP.NET MVC: https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4

  • His answer was very satisfactory, I did not know the suffix, the await or the task for example. But his answer already gave me a north. Thanks !

  • I will add a microsoft link about asynchronous request.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.