Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an async call in an MVC 5 action filter

The problem

I have an api GET method to retrieve site configuration. I am using httpClient and the GetAsync() method to do this.

HttpResponseMessage response = await client.GetAsync("api/{0}/config", id);

As I need this configuration across the site, I planned to use a global action filter for this.

Question

How can I call an async method in an MVC action filter? Or is there a better solution to this problem?

I have looked at multiple SO questions (Async action filter in MVC 4) on this but I not found a satisfactory solution.

like image 309
Colin Bacon Avatar asked Jan 19 '15 12:01

Colin Bacon


People also ask

How do you call async method in MVC action?

STEP 01 Create new MVC Application project, named as "Async". In the File menu, click New Project. In the "New Project" dialog box, under Project types, expand Visual C#, and then click "Web". In the Name box, type "Async", then click on Ok.

How do you call async task ActionResult?

1 Answer. Show activity on this post. It is best for you to use async/await down the whole call stack which is possible with MVC. Mark your Action as async and then use the await keyword to wait for the results from the CsvReader method.

When would you use asynchronous actions?

Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.

How many types of filters are there in MVC 5?

The ASP.NET MVC framework supports four different types of filters: Authorization filters – Implements the IAuthorizationFilter attribute.


1 Answers

There is no way to (reliably) call an asynchronous method from an ASP.NET MVC 5 action filter. This has already been fixed in ASP.NET vNext, but AFAIK there are no plans to support this in MVC 5.

If you absolutely must do this in an action filter, then you must use synchronous calls (e.g., WebClient instead of HttpClient).

like image 157
Stephen Cleary Avatar answered Oct 19 '22 19:10

Stephen Cleary